Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSONP data returned from remote server

I am trying to grab some data via JSONP. Using Firebug, I am able to see the data properly being returned, but I am having a hard time thinking how I have to parse it. The data return is really a nested array correct? someFunction is the name of the callback function. This is how the data looks:

someFunction([  
{  
       "title":"Sample Title",  
       "link":"http://example.com",  
       "description":"Sample Description",  
       "publisher":"Sample Publisher",  
       "creator":"Sample Author",  
       "date":"Thu, 19 Aug 2010 12:41:29 GMT",  
       "num_pages":10,  
       "num_results":"10"  
},  
]);

Just a little confused about how to properly parse and output.

like image 793
patricksweeney Avatar asked Aug 22 '10 21:08

patricksweeney


People also ask

How do I get JSONP data?

Method to use JSONP:In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.

What is a JSONP response?

The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

What is JSONP data type?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

How does JSONP request work?

Standard JSON Asynchronous requestThe browser makes an asynchronous POST request to the server slapping its parameters to the service in the body. The server responds with a string of JSON data. A success handler of the request fires and the string is converted into a Javascript Object to be used in the application.


2 Answers

You don't have to parse the data. It is already a valid JavaScript object. For instance, to print the description property for the first object inside someFunction

function someFunction(result) {
    alert(result[0].description); // alerts "Sample Description"
}
like image 133
Anurag Avatar answered Sep 21 '22 22:09

Anurag


Write a function with the correct name and the correct arguments. The JS engine will do the parsing for you.

function someFunction(data) {
    // Now data is an Array, containing a single
    // Object with 8 properties (title, link, etc)
}
like image 42
Quentin Avatar answered Sep 22 '22 22:09

Quentin