jQuery Ajax响应错误 [英] Jquery ajax response error
问题描述
这里是我要实现的目标的部分示例.
Here is a partial example of what I am trying to achieve.
我正在尝试从ajax检索值,但是javascript result.success变量未定义.我有以下内容:
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
我从ajax(从chrome开发工具中检索到)得到的响应是{"success":true,"html":"Test"}
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
这对我来说很好,但是在JavaScript结果中.成功是未定义的.我相信这很简单,我只是看不出问题出在哪里.
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
推荐答案
您的错误在这里:
datatype: 'json',
JavaScript区分大小写,属性为dataType
:
Javascript is case sensitive and the property is dataType
:
dataType: 'json',
因此,没有告知jQuery自动解析JSON,因此结果仅被视为html或纯文本.
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
您还需要删除content-type标头,因为它指定了请求(非响应)的内容类型.您正在发送请求中编码的表单/URL,而不是JSON.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
这篇关于jQuery Ajax响应错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!