views:

238

answers:

2

Hi - 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(url, 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!

+1  A: 

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.

David Dorward
ah I see what you mean: yes, @Gregory, your server is returning plain JSON, and is not paying attention to the "callback" parameter.
Pointy
A: 

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"
 }
})
Luca Matteis
So will "callback" be added before the parenthesis?
Gregory