意外的令牌:尝试解析JSON字符串时

jQu*_*ast 2 jquery json

我试图解析这个JSON字符串:

{ "RESULTS": [ { "name": "Thessaloniki GR", "type": "Sailing", "l": "/sailing-weather/beach:Porto%20Carras%20Marina 45904" }, { "name": "Thessaloniki, Greece", "type": "city", "c": "GR", "zmw": "00000.1.16622", "tz": "Europe/Athens", "tzs": "EET", "l": "/q/zmw:00000.1.16622" } ] }
Run Code Online (Sandbox Code Playgroud)

这是从这里检索的

这是我的片段:

$(document).ready(function () {

  $("#w11").autocomplete({
        source: function (a, b) {
            $.ajax({
                url: "http://autocomplete.wunderground.com/aq",
                dataType: "jsonp",
                data: {
                    format: "jsonp",
                    query: a.term
                },
                success: function (a) {
                    for (i in data.RESULTS) {
                        console.log(data.RESULTS);
                    }
                }
            })
        }
    });


});?
Run Code Online (Sandbox Code Playgroud)

这给了我Uncaught SyntaxError: Unexpected token :第一行的错误{ "RESULTS": [

我如何解析JSON结果?

T.J*_*der 9

你告诉jQuery期待JSON-P,而不是JSON:

dataType: "jsonp"
Run Code Online (Sandbox Code Playgroud)

...但结果是JSON.JSON-P和JSON是根本不同的东西.这是一个JSON响应示例:

{"foo": 42}
Run Code Online (Sandbox Code Playgroud)

以下是JSON-P响应的样子:

callback({"foo": 42});
Run Code Online (Sandbox Code Playgroud)

要么

callback({foo: 42});
Run Code Online (Sandbox Code Playgroud)

如果http://autocomplete.wunderground.com/a与运行代码的文档不在同一原点,则由于相同原始策略,您将无法通过ajax从中检索JSON (除非有问题的服务器支持CORS,否则允许您的原始请求,用户也支持CORS的浏览器).我怀疑这就是为什么你试图使用JSON-P,它起源于交叉起源.但问题是,服务器也必须支持JSON-P.尽管format=jsonp在URL中,服务器没有使用JSON-P响应,但使用JSON.

在评论中,您链接到他们的API文档,这表明他们确实支持JSON-P,只是在URL中使用非标准参数名称(cb而不是更常见callback).

所以这应该工作(我还修复了我在问题评论中提到的代码问题):

$.ajax({
    url:      "http://autocomplete.wunderground.com/aq",
    dataType: "jsonp",
    jsonp:    "cb",     // <================= New bit is here
    data:     {
        format: "json", // <=== "json" not "jsonp" according to the docs, but I think the "cb" argument overrides it anyway
        query:  a.term
    },
    success:  function (data) { // <=== `data`, not `a`
        var i;
        for (i in data.RESULTS) {
            console.log(data.RESULTS[i]); // <=== Use [i] here
        }
    }
}); // <=== Semicolon was missing
Run Code Online (Sandbox Code Playgroud)

事实上它确实有效:实例 | 资源

jsonp参数告诉jQuery用于定义JSON-P回调名称的URL参数.默认值是标准,callback但API使用非标准参数.