Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONP how to retrieve text

Tags:

jquery

jsonp

I do understand what JSON/JSONP does, but I'm not a programmer and do not know how to extract the bare basics for simple usage. I've read a lot on JSONP and lots of examples on various usage for JSONP, but I have yet to find a simple example for retrieving text from another page (e.g. http://www.domain.com/external/text.aspx).

Could somebody please give an example of a jQuery/JSONP setup for retrieving text into a div? I would think that is a very basic use of JSONP.

like image 208
Nano Avatar asked Mar 23 '10 12:03

Nano


1 Answers

First, it's important to understand that for JSONP to work, the server must know that it's going to be contacted with a JSONP request. In other words, you can't just make a request to some random server and expect it to work if the server is not prepared properly.

If you do know of a server with a URL that is designed to accept and respond to JSONP requests, then what it will return to you is a JSON expression wrapped in a call to a function. Your page will include that function, and so when the results come back from the server the browser will interpret the JSON expression and then invoke the function.

Thus, if you want to make a service that returns a nice block of text, you'll invoke the service like this:

$.getJSON("http://www.domain.com/external/text.aspx?callback=", function(data) {
  $('#targetDiv').text(data.text);
});

The jQuery code will prepare everything such that the server will be told (via a parameter called "jsonp" in the HTTP request) the name of the function to call (and jQuery itself will build that function for you). The server should respond with something like this:

jqueryFunctionName({text: "This is a nice block of text."})
like image 154
Pointy Avatar answered Oct 11 '22 18:10

Pointy