Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsonp with jquery [closed]

Tags:

jquery

ajax

jsonp

Can you give a very simple example of reading a jsonp request with jquery? I just can't get it to work.

like image 639
akula1001 Avatar asked Apr 21 '10 08:04

akula1001


People also ask

Is JSONP deprecated?

Yes, JSONP is obsolete now. There's absolutely no reason to offer a JSONP service anymore.

Why is JSONP avoided?

JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known. This means it's best suited for consumption of public data feeds.

What is JSONP jQuery?

JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data. It does this by having the server return JSON data wrapped in a function call (the “padding”) which can then be interpreted by the browser.

What is difference between JSON and JSONP?

Json is stardard format that is human readable used to transmit information from one server to another server. Jsonp is a json with ability to transmit information to another domain. JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it.


1 Answers

Here is working example:

<html><head><title>Twitter 2.0</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head><body> <div id='tweet-list'></div> <script type="text/javascript"> $(document).ready(function() {     var url =  "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";     $.getJSON(url + "?callback=?", null, function(tweets) {         for(i in tweets) {             tweet = tweets[i];             $("#tweet-list").append(tweet.text + "<hr />");         }     }); }); </script> </body></html> 

Notice the ?callback=? at the end of the requested URL. That indicates to the getJSON function that we want to use JSONP. Remove it and a vanilla JSON request will be used. Which will fail due to the same origin policy.

You can find more information and examples on the JQuery site: http://api.jquery.com/jQuery.getJSON/

like image 65
Tomas Sedovic Avatar answered Sep 21 '22 17:09

Tomas Sedovic