JSONP how to get text

I really understand that JSON / JSONP, but I am not a programmer and do not know how to extract simple basics for easy use. I read a lot in JSONP and many examples of various uses for JSONP, but I still have to find a simple example for extracting text from another page (for example, http://www.domain.com/external/text.aspx ).

Can someone please provide an example of installing jQuery / JSONP to extract text in a div? I would think that this is a very simple use of JSONP.

+6
jquery jsonp
source share
1 answer

First, it is important to understand that for JSONP to work, the server must know that a JSONP request will be associated with it. In other words, you cannot just send a request to some random server and expect it to work if the server is not prepared properly.

If you know 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 enclosed in a function call. Your page will include this function, and therefore, when the results return from the server, the browser interprets the JSON expression and then calls the function.

Thus, if you want to make a service that returns a good block of text, you will call the service as follows:

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

The jQuery code will prepare everything so that the server (via the jsonp parameter) in the HTTP request is given the name of the function being called (and jQuery itself will build this function for you). The server should respond something like this:

 jqueryFunctionName({text: "This is a nice block of text."}) 
+13
source share

All Articles