最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "invalid label" when using JSONP? - Stack Overflow

programmeradmin2浏览0评论

I've got a problem with my JSONP request.. The data won't be displayed, Firebug shows an "invalid label" error..

My 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>");
    });
}

My JSON:

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

My 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>

The request works fine, but anyway the data isn't displayed.

Im searching for a solution for days.. Can somebody help me? Thank you in advance!

SOLUTION (update: 06.09.12)

I've solved this problem. The server (REST interface) on which the was executed had no callback function implemented.. Another way to set up crossdomain requests WITHOUT using JSONP is to set the following jquery variable:

jQuery.support.cors = true;

I've got a problem with my JSONP request.. The data won't be displayed, Firebug shows an "invalid label" error..

My 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>");
    });
}

My JSON:

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

My 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>

The request works fine, but anyway the data isn't displayed.

Im searching for a solution for days.. Can somebody help me? Thank you in advance!

SOLUTION (update: 06.09.12)

I've solved this problem. The server (REST interface) on which the was executed had no callback function implemented.. Another way to set up crossdomain requests WITHOUT using JSONP is to set the following jquery variable:

jQuery.support.cors = true;
Share Improve this question edited Sep 6, 2012 at 8:22 P4tR asked Apr 10, 2012 at 6:22 P4tRP4tR 1142 silver badges13 bronze badges 4
  • 1 This is because JSON is not a valid JS program but it is trying to be used as one. Find out why the JSONP isn't working as expected. (btw, getRessources looks like a misspelling.) – user166390 Commented Apr 10, 2012 at 6:25
  • the request works fine.. i've added an image with the response.. – P4tR Commented Apr 10, 2012 at 6:33
  • 2 The response isn't JSONP, it is JSON. JSONP responses are supposed to be wrapped inside a function call like callback({"foo": "bar"}) – Salman Arshad Commented Apr 10, 2012 at 6:34
  • 1 The server you sent the request to doesn't seem to support JSONP requests, or you don't perform the call correctly. – Anders Marzi Tornblad Commented Apr 10, 2012 at 6:34
Add a ment  | 

2 Answers 2

Reset to default 7

The response to a JSONP call needs to wrap the JSON itself in a function call, where the name of the function being called is usually supplied in the url. jQuery automatically adds a query string parameter of "callback" to the URL that is being requested, so the script on your server should do something similar to:

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

The reason for adding the name of a function to the response is that a JSONP request is actually a script tag appended to the DOM rather than a regular request that would be made by an XMLHttpRequest object. Using JSONP allows the browser to make cross-domain requests that would otherwise be blocked by the cross-domain policy that applies (by default) to an XHR.

If the AJAX script is hosted on same domain then you can use dataType: "json" like this:

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
});​

If the AJAX script is hosted on another domain then the server must return JSONP data -- the JSON data wrapped inside a function call:

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

If the server returns bare JSON data then you will get parsing errors because a JSONP requests is roughly similar to injecting a <script src="..."> tag. To understand why bare JSON object literal causes parse error, consider these examples:

// 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"
})​
发布评论

评论列表(0)

  1. 暂无评论