Jquery ajax响应错误

这是我想要实现的部分例子。

我试图从ajax中检索一个值,但是javascript result.success变量是未定义的。 我有以下内容:

PHP:

$result = array ("success" => null, "html" => ""); $result['success'] = true; $result['html'] = "test"; echo json_encode($result); 

使用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 dev工具中检索)获得的响应是​​{“success”:true,“html”:“Test”}

这看起来很好,但是在JavaScript result.success中是未定义的。 我相信这很简单我只是看不出问题在哪里。

你的错误在这里:

 datatype: 'json', 

Javascript区分大小写,属性为dataType

 dataType: 'json', 

因此,jQuery没有被告知自动解析JSON,因此结果只被视为html或纯文本。

您还需要删除content-type标头,因为它指定了请求不响应的内容类型。 您正在发送请求中编码的表单/url,而不是JSON。

 $.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 } } // Maybe your forgot this }); 

换句话说 – 基本调试

在您的PHP页面中将它放在页面顶部(您只接受json响应,但可能您的响应标头内容类型是text / html

 header('Content-type: application/json');