开发者

jQuery + JSONP return data empty?

I need to access data on a subdomain I've been trying to use JSONP which jQuery has support for. The data that I'm accessing on the subdomain is a static (regenerated) .json file (http://www.example.com/data.json)

I was running into "Invalid Label Error" errors and realized the data needed to be wrapped in parenthesis and use ?callback=?

http://www.example.com/data.json?callback=?

({
 "items": [
 {   
  "url": "http://www.example.com",
  "id": "2981",
        "title": "title",
  "description": "lorem ipsum sit dolor",
  "start": "00:10:00",
   "end": "00:20:00"
 }
})


$.getJSON(ur开发者_Go百科l, function(data){
 console.log("json: " + data);
});

Wrapping the data in () worked as I'm now able to see the data returned in the NET tab of Firebug, but the $.getJSON doesn't return anything, I don't think it fires.

What am I missing? Does something more need to be done server-side?

Thanks!


The data you are returning isn't JSON-P.

Wikipedia has a decent explanation of what JSON-P should look like. There is a jQuery specific guide to accepting JSON-P.


The code that you're returning from the HTTP request is being executed by the browser.

The browser executes it fine, but it doesn't know where to put it because it isn't assigned to anything.

Fortunately jQuery is smart enough, and let's you use a parameter (callback=?) for you to use in your code.

Your server side language must add that callback parameter and make your JSON response look like a JavaScript function call:

<?php echo $_GET["callback"]?>({
 "items": [
 {   
  "url": "http://www.example.com",
  "id": "2981",
        "title": "title",
  "description": "lorem ipsum sit dolor",
  "start": "00:10:00",
   "end": "00:20:00"
 }
})


if you try to validate your JSON data for example on http://jsonlint.com/ you see that there are some errors.

Do you generate the JSON data by a framework or manually.

Manual JSON data generation is error prone.

I hope helps you to fix your error.

Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜