【问题标题】:Ajax call throws parse errorAjax 调用引发解析错误
【发布时间】:2013-01-15 12:07:21
【问题描述】:

尝试执行以下调用时出现解析错误:

       $.ajax({
        cache: true,
        url: "http://localhost:3000/app/test/result1",
        data: "{}",
        type: "GET",
        jsonpCallback: "testCall",
        contentType: "application/jsonp; charset=utf-8",
        dataType: "jsonp",
        error: function (xhr, status, error) {
            alert(error);
        },
        success: function (result) {
            alert(result);
        },
        complete: function (request, textStatus) {
            alert(request.responseText);
            alert(textStatus);
        }
    });               

如果我直接在浏览器地址栏中粘贴请求url,返回的结果似乎是有效的JSON:

    {
      "name": "The Name",
      "description": "The Description"
    }

我正在使用 IISnode、NodeJs 和 Express JS。我已经测试了这两种情况:

    // NODE JS CODE

    var app = express(); 

    app.get('/app/test/result1', function (req, res) {
    res.send({ name: "The Name", description: "The Description" });
    });

    app.get('/app/test/result2', function (req, res) {
    res.send(JSON.stringify({ name: "The Name", description: "the Description" }));
    });

感谢任何建议,提前致谢。

【问题讨论】:

  • 你能用开发者工具栏/firebug之类的工具来监控ajax请求和响应吗

标签: json jquery cross-domain jsonp parse-error


【解决方案1】:

您的数据类型列为jsonp。但是,您来自 node.js 的响应不是格式正确的 JSON-P 响应。 JSON-P 响应需要包装在回调中,如下所示:

testCall({ name: "The Name", description: "The Description" });

node.js 代码如下所示:

res.send(
    'testCall(' + 
    JSON.stringify({ name: "The Name", description: "the Description" }) +
    ');'
);

(另请注意,您不需要 data: "{}" 行,因为该请求是一个 GET 请求并且不包含任何数据。它不应该伤害任何东西,但最好删除以避免混淆)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多