- Recipe: Setting Up an Example Server in Node.js
- Recipe: Performing a GET Request
- Recipe: Loading HTML Directly
- Recipe: Handling the Result by Using Promises
- Recipe: Handling Server Errors
- Recipe: Catching Page-not-Found Results
- Recipe: Handling Page Redirects
- Recipe: Setting Request Timeouts
- Recipe: Passing HTTP Headers
- Example: Validating Form Input on the Server Side
- Recipe: Loading XML
- Recipe: Listening to AJAX Events
- Recipe: Reading JSONP from an External Server
- Summary
Recipe: Reading JSONP from an External Server
Classic AJAX works with the XmlHttpRequest (XHR) object. Most browsers do not allow XHR to access other servers than the origin of the current page. To work around this limitation, JSONP was invented.
JSONP is JSON wrapped inside a function call. Instead of making an AJAX request, a script element pointing to the JSONP script is added inside the HTML document and a callback function is called to access the script.
Listing 5.13 demonstrates how to retrieve data from Twitter by using JSONP. Keep in mind that error handling does not work with JSONP.
Listing 5.13. Connecting to Twitter and Searching for jQuery-Related Posts
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>Get JSONP</title> 05 </head> 06 <body> 07 08 <h2>Press the button to perform the request.</h2> 09 10 <button id="trigger">GET</button> 11 <br> 12 <div id="target"> 13 14 15 <script src="https://code.jquery.com/jquery-1.7.2.min.js"></script> 16 17 <script> 18 // please externalize this code to an external .js file 19 $(document).ready(function() { 20 21 $('#trigger').click(function() { 22 23 $.getJSON('http://search.twitter.com/search.json' + 24 '?q=jquery&callback=?', function(data) { 25 26 $.each(data.results, function(index, value) { 27 28 $('#target').append(value.text + '<br>'); 29 30 }); 31 32 }); 33 34 }); 35 36 }); 37 </script> 38 </body> 39 </html>
By default, the JSONP handler in jQuery looks for a callback=? parameter in the query string. The ? is replaced with a jQuery-generated callback function to be inserted into JSONP by the server.
You can modify settings if the parameter has another name than callback or when the callback method is not parameterized. If you insist, you can find these parameters in the jQuery online documentation.
The best advice is to avoid JSONP whenever possible.