JSON (Ajax) and jsonp

Source: Internet
Author: User

When developing a web application, we inevitably use some ajax to Implement Asynchronous Data Loading to build rich clients.

However, there is a problem with Ajax: The same-origin policy may make us unable to obtain the required data.

(Note: The same-origin policy means that the Ajax requester and the data responder must be at the same IP address and port. For example, if our webpage address is under 127.0.0.1: 8080, the Ajax request initiated by the client can only be received and processed by the listener of the IP address and port. Some netizens pointed out that multiple IP addresses of the same host cannot send Ajax requests to each other. I have not verified this .)

Due to the same origin policy of Ajax, we may not be able to obtain the required data in the following cases (for Ajax ):

1. You need to use scripts (JavaScript) on the page to retrieve data from other servers (unlike WebService, we generally use HTTP requests in the background to retrieve data and then return it to the browser ).

2. You need to save the webpage locally (offline) and use a script to obtain data from the server when loading the webpage in the browser.

In particular, the second type is very suitable for mobile application development today. Thanks to the excellent support provided by various mobile device platforms, HTML5 and css3 standard web pages can even rival local applications, and their cross-platform features are more advantageous than local applications!

 

After talking about the limitations of Ajax in "cross-origin", we have to use some skills to implement asynchronous loading and cross-origin.

Jsonp is a skill or usage mode. It also uses the JSON format for data transmission, but this is not necessary (as is Ajax ).

 

When Ajax cannot be used for cross-origin, we find that:

1. Common HTTP requests can be cross-origin.

2. <SCRIPT src = ""> </SCRIPT>, <link ref = ""/>, and these tag data are loaded using HTTP requests, it is not synchronous (I have not studied much here. If you are interested, you can try to read the WebKit browser kernel source code )!!!

Can we use the script tag to implement cross-Origin data requests? The answer is yes!

We know that data requests must have certain rules. Essentially, web pages, images, CSS, and JS are implemented using HTTP requests (usually get, the server program will return the corresponding data (such as JS script content, CSS style table content, and image content), except that the resource file requests are ignored during the logic design of the server program, let the server program handle it by default.

 

So far, the cross-origin principle of jsonp is clear: Use the <SCRIPT> </SCRIPT> label to generate HTTP (get) request to obtain data from the server (we usually request a specific resource file, such as jquery. by default, the server program returns the corresponding file to the browser as a string for processing. Now we need to request a specific controller, let the string returned by the server program contain the data we need ).

 

To make it easier for readers to understand, I drew a sketch:

It is never hard to see: we asked JavaScript to help us bring back data.

 

The following is the specific code: if you do not understand it very well, you can use callback as a breakthrough. After understanding it, jsonp is clearly presented to you.

1 <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> 2 <HTML> 3 

(The above code is a local HTML webpage, that is, the webpage is not accessed by entering the address bar of the browser)

1 Public void doget (httpservletrequest request, httpservletresponse response) 2 throws servletexception, ioexception {3 response. setcharacterencoding ("GBK"); 4 response. setcontenttype ("text/JavaScript"); 5 printwriter out = response. getwriter (); 6 string JSON = "{\" ID \ ": \" 100 \ ", \" Name \ ": \" Zhang San \"}"; 7 string callback = request. getparameter ("Callback"); 8/* try {9 thread. sleep (3000); 10} catch (interruptedexception e) {11 E. printstacktrace (); 12} */13 out. write (callback + "(" + JSON + ")"); 14 out. flush (); 15 out. close (); 16}

(The above Code can be used to return the script string and bring back data at the same time. You only need to define the callback function name on the client and server)

 

You are welcome to move to our chat group and pass the time together when you are bored:

Or contact me via QQ:

(Last editing time: 22:44:57)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.