【发布时间】:2015-04-01 15:26:18
【问题描述】:
我的 PHP 返回的 JSON 是:
{"success":0,"message":"Error: No entityId pass!"}
我的 javascript 仍然告诉我“SyntaxError: Unexpected end of input”。
PHP:
...
//check if an image id was passed for removal in the POST data
if ( isset($_POST["entityId"])) {
$entityId = $_POST["entityId"];
}
else {
//setup response json
$resp = array();
$resp['success'] = 0;
$resp['message'] = "Error: No entityId passed!";
header('Content-Type: application/json');
echo json_encode($resp);
}
...
JS:
// send xhr request
$.ajax({
dataType: 'json',
type: $theForm.attr('method'),
url: $theForm.attr('action'),
data: $theForm.serialize(),
success: function(data) {
//backend returns a json with variable success either true or false.
resp = data;
if(resp.success == 1) {
//render gallery anew
}
else {
console.log(data);
if (data.message) {
$(self).find('.VanillaGallery-overlayContentWrapper').html(data.message);
}
else {
$(self).find('.VanillaGallery-overlayContentWrapper').html('Oops! Något gick fel, felmeddelande saknas dock.');
}
}
},
error: function(xhr, status, text) {
$(self).find('.VanillaGallery-overlayContentWrapper').html('Oops! Något gick fel...<br />'+text);
}
});
很奇怪。我的标头会有所不同,具体取决于请求是通过 ajax 还是作为直接在浏览器中的普通单独请求(而不是通过 ajax)发出:
通过 ajax 看起来像这样的标题:
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Wed, 01 Apr 2015 17:48:26 GMT
Keep-Alive:timeout=5, max=97
Server:Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8zc DAV/2 PHP/5.5.3
X-Pad:avoid browser bug
X-Powered-By:PHP/5.5.3
直接从浏览器地址栏通过这个:
Connection:Keep-Alive
Content-Length:52
Content-Type:application/json
Date:Wed, 01 Apr 2015 17:42:23 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8zc DAV/2 PHP/5.5.3
X-Powered-By:PHP/5.5.3
【问题讨论】:
-
您是否检查了开发人员工具以验证 HTTP 响应是否真的像您认为的那样?
-
可能是我的本地主机(MAC 上的 Apache,MAMP)未配置为提供正确的 JSON 响应
-
我在 Chrome 中的网络日志显示 'application/json' 这是否意味着服务器 (localhost) 正在提供正确的 json 响应?
-
我很确定 jQuery 不会关心内容类型标题的内容。如果你告诉它它是 JSON,它会尝试解析它。开发人员工具中的网络选项卡将让您看到您的服务器是否真的发回了您认为的响应。换句话说,您将看到 实际 响应内容。
-
我添加了回复。为什么它在一个实例中被解释为 application/json,而在通过 ajax 时被解释为 text/html?
标签: javascript jquery ajax syntax