使用JSONP时“无效标签”?

时间:2012-04-10 06:22:51

标签: javascript ajax json jsonp syntax-error

我的JSONP请求有问题.. 数据将不会显示,Firebug显示“无效标签”错误..

enter image description here

我的JavaScript:

$.ajax({
    url: link,
    dataType: "jsonp",
    beforeSend: function(xhr) {
        var base64 = btoa(username + ":" + password);
        xhr.setRequestHeader("Authorization", "Basic" + base64);
        xhr.overrideMimeType("application/json");
    },
    jsonpCallback: "getResources"
})

function getResources(data) {
    alert(data);
    alert(JSON.parse(data));
    $.each(data.groupStatus, function(i, item) {
        $("body").append("<p>ID: " + item.id + "</p>");
    });
}

我的JSON:

{
    "groupStatus": [
        {
            "id": "Application Layer Configuration-ApplicationLayer",
            "time": 1332755316976,
            "level": 0,
            "warningIds": [],
            "errorIds": []
        },
        {
            "id": "Application Layer-ApplicationLayer:nscalealinst2",
            "time": 1333431531046,
            "level": 0,
            "warningIds": [],
            "errorIds": []
        }
    ]
}

我的HTML:

<html>
<head>
    <title>Monitor</title>
    <link href="css/gadget.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
</head>
<body>
    <div id="content"></div>
    <script type="text/javascript" src="js/gadget.js"></script>
</body>

请求正常,但无论如何都不会显示数据。

enter image description here

我在寻找解决方案好几天..有人可以帮帮我吗?提前谢谢!

解决方案(更新:06.09.12)

我已经解决了这个问题。执行了的服务器(REST接口)没有实现回调函数。 在不使用JSONP的情况下设置跨域请求的另一种方法是设置以下jquery变量:

jQuery.support.cors = true;

2 个答案:

答案 0 :(得分:7)

对JSONP调用的响应需要在函数调用中包装JSON本身,其中被调用的函数的名称通常在url中提供。 jQuery会自动将“callback”的查询字符串参数添加到正在请求的URL中,因此服务器上的脚本应该执行类似的操作:

// assuming that $JSON contains your JSON content
print "{$_REQUEST['callback']}( {$JSON} );";

将函数名称添加到响应的原因是JSONP请求实际上是附加到DOM的脚本标记,而不是由XMLHttpRequest对象生成的常规请求。使用JSONP允许浏览器发出跨域请求,否则这些请求将被应用(默认情况下)XHR的跨域策略阻止。

答案 1 :(得分:1)

如果AJAX脚本托管在同一个域中,那么您可以使用dataType: "json",如下所示:

function getResources(data, textStatus, jqXHR) {
    console.log(data);
    // no need to do JSON.parse(data)
    $.each(data.groupStatus, function(i, item) {
        $("body").append("<p>ID: " + item.id + "</p>");
    });
}
$.ajax({
    url: link,
    dataType: "json",
    beforeSend: function(xhr) {
        var base64 = btoa(username + ":" + password);
        xhr.setRequestHeader("Authorization", "Basic" + base64);
        xhr.overrideMimeType("application/json");
    },
    success: getResources
});​

如果AJAX脚本托管在另一个域上,那么服务器必须返回JSONP数据 - 包含在函数调用中的JSON数据:

callback(
    {
        "groupStatus": []
    }
);​

如果服务器返回裸JSON数据,那么您将获得解析错误,因为JSONP请求与注入<script src="...">标记大致相似。要理解为什么裸JSON对象文字会导致解析错误,请考虑以下示例:

// WORKS
{
    alert("foo");
}

// PARSE ERROR -- quote from MDN:
// You should not use an object literal at the beginning of a statement.
// This will lead to an error or not behave as you expect, because the { 
// will be interpreted as the beginning of a block.
{
    "foo": "bar"
}

// WORKS
callback({
    "foo": "bar"
})​