Ajax调用返回错误状态200和状态文本确定
我正在处理用户发送图像和注释的窗体。无论发生什么情况,ajax调用都会直接发生错误(即使文件和注释已成功上载并写入数据库)。Ajax调用返回错误状态200和状态文本确定
我试图登录错误的反馈,这是我收到:
Object {readyState: 4, responseText: "<pre class='xdebug-var-dump' dir='ltr'>↵<b>array</…DstagramPost succesfully made.{"check":"success"}", status: 200, statusText: "OK"}
这是我的Ajax调用:
<script type="text/javascript">
$(document).ready(function(){
$("#postSubmit").on("click", function(e){
$.ajax({
url: "ajax/postUpload.php",
type: "POST",
data: new FormData($("#postForm")[0]),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
},
error: function (request, status, error) {
console.log(request);
alert('Something is wrong');
}
});
e.preventDefault();
});
});
</script>
我的PHP代码:
<?php
include_once("../classes/Post.class.php");
session_start();
$post = new Post();
var_dump($_FILES);
if(!empty($_POST)){
$file_tmp_name = $_FILES['postImage']['tmp_name'];
$post->checkIfImage();
$post->checkFileSize();
$post->checkFileFormat();
$post->checkAspectRatio();
if(!$post->checkIfImage()){
$uploadStatus['image'] = "false";
}
if(!$post->checkFileSize()){
$uploadStatus['size'] = "false";
}
if(!$post->checkFileFormat()){
$uploadStatus['format'] = "false";
}
if(!$post->checkAspectRatio()){
$uploadStatus['ratio'] = "false";
}
if($post->checkIfImage() && $post->checkFileSize() && $post- >checkFileFormat() && $post->checkAspectRatio()){
$result = $post->createPost($file_tmp_name);
$uploadStatus['check'] = "success";
}else{
$uploadStatus['check'] = "error";
}
header('Content-Type: application/json; charset=utf-8', true);
echo json_encode($uploadStatus);
}
?>
因此,总结一下,如果图像通过了像checkIfImage()这样的所有要求,它会将其上传到一个文件夹,并将图像路径d描述发布在数据库中。如果它没有通过所有的要求,它不会在那里发布。不过,我每次都会遇到错误。
如果我删除的数据类型:它转到错误“JSON”的一部分,如果我将其更改为别的我得到以下输出:
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'postImage' <font color='#888a85'>=></font>
<b>array</b> <i>(size=5)</i>
'name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'passfoto.png'</font> <i>(length=12)</i>
'type' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'image/png'</font> <i>(length=9)</i>
'tmp_name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'D:\xampp\tmp\phpDFE9.tmp'</font> <i>(length=24)</i>
'error' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>0</font>
'size' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>112825</font>
</pre>D:\xampp\htdocs\IMDstagramPost succesfully made.{"check":"success"}
的一部分,我需要的是当然的检查,所以我可以例如清除表单,如果检查=成功或给出错误,如果它不是..
问题是因为你有一些HTML,你输出在你的PHP文件之前,你echo
的JSON。您可以在JSON中看到response
参数:
<pre class='xdebug-var-dump' dir='ltr'>↵<b>array</…DstagramPost succesfully made.
删除该HTML。响应文本应该是只这个JSON格式的字符串:
{"check":"success"}
太棒了!像魔术一样工作,我没有想到从我的Post类中删除回声。再次感谢! –
没问题,很乐意帮忙 –
查看错误信息,它会告诉你这个问题。如果Ajax调用良好,则无法解析您的JSON数据。 – epascarello
是的,谢谢,我发现了这个问题! :) –