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.
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.
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.
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.
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.
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"
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With