【问题标题】:Jquery ajax response errorJquery ajax响应错误
【发布时间】:2013-07-05 13:14:39
【问题描述】:

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

我正在尝试从 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 开发工具中检索)得到的响应是 {"success":true,"html":"Test"}

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

【问题讨论】:

  • 试试'result = $.parseJSON(result);'看看它是否仍然未定义

标签: php jquery ajax json


【解决方案1】:

你的错误在这里:

datatype: 'json',

Javascript 区分大小写,属性为dataType:

dataType: 'json',

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

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

【讨论】:

  • 感谢您的帮助!我将内容类型标头作为其他人的建议来解决问题,所以我现在将其删除。正如您所期望的那样,问题是 dataType 是小写的。再次感谢您的建设性回应。 :)
【解决方案2】:
$.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
        });

换句话说 - 基本调试

【讨论】:

  • 什么!?!?! datatype=json 你解析它?
  • 我错过了这里的 } 但它在我的代码中看起来我的问题是数据类型而不是数据类型.. :(
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多