Ajax cross-domain request JSONP get JSON data

Source: Internet
Author: User
Tags script tag

Cross-domain request for Ajax encountered a problem was found in the following solution:

Content Reference : http://justcoding.iteye.com/blog/1366102


This method does not allow cross-domain communication because it is restricted by the browser. If you try to request data from a different domain, a security error occurs. These security errors can be avoided if you have control over the remote server where the data resides and each request goes to the same domain. But what is the use of WEB applications if you only stay on your own servers? What if you need to collect data from multiple third-party servers?

Understanding the same Origin strategy

The same-origin policy prevents scripts loaded from one domain from getting or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is very old and exists from Netscape Navigator version 2.0.

A relatively simple way to overcome this limitation is to have the Web page request data to the Web server it originates from, and have the Web server forward requests to a true third-party server like a proxy. Although the technology has been widely used, it is not scalable. Another way is to use frame features to create a new zone in the current Web page, and use the GET request to get any third-party resources. However, when resources are obtained, the content in the framework is limited by the same-origin policy.

The best way to overcome this limitation is to insert a dynamic script element into a Web page that points to a service URL in another domain and gets the data in its own script. It starts executing when the script loads. This approach is possible because the same-origin policy does not prevent dynamic script insertions and considers the script to be loaded from the domain that provides the Web page. However, if the script tries to load a document from another domain, it will not succeed. Fortunately, this technique can be improved by adding JavaScript Object Notation (JSON).

1. What is JSONP?

To understand JSONP, you have to mention JSON, so what is JSON?

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

2. What is the use of JSONP?

Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then output JSON data on the server and execute callback functions to resolve cross-domain data requests.


3, Jsonp principle
First register a callback with the client and then pass the callback name to the server.

at this point, the server becomes JSON data.
then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

4, JSONP Advantages and disadvantages

JSONP is a powerful technology for building mashups, but unfortunately it is not a panacea for all cross-domain communication needs. It has some drawbacks that must be carefully considered before submitting development resources.

First, and most important, there is no error handling on the JSONP call. If the dynamic script insert is valid, the call is executed, and if it is not valid, the silence fails. There is no hint of failure. For example, you cannot catch a 404 error from the server, and you cannot cancel or restart the request. However, waiting for a period of time has not responded, do not have to ignore it. (The future JQuery version may have the feature to terminate the JSONP request.)

Another major drawback of JSONP is the danger of being used by untrusted services. Because the JSONP service returns a JSON response packaged in a function call, the function call is executed by the browser, which makes the host WEB application more susceptible to various types of attacks. If you intend to use the JSONP service, it is important to understand the threats it can pose.



Specific implementation:

The foreground Ajax request adds a line to the AJAX function DataType: ' Jsonp ', which is marked as cross-domain requests as follows:

</pre><pre name= "code" class= "Java" ><script>function Sendjson () {var value = $ ("#xiaoh"). Val (); alert (value); $.ajax ({   type: ' Post ',   dataType: ' Jsonp ',   url  : ' Http://localhost:8080/springMVC/jsonDo ',         Data: {' Tokenid ': value},   success:function (data) {      alert (Data.tokenid)       },       error:function (data) { C9/>alert (Data.tokenid);}}       );        } </script>

The background code of the action should also be handled accordingly, as follows

Add the String callback parameter to the parameter value of the Jsondo, this parameter is not assigned in the foreground Ajax, jquery will automatically assign a value to this parameter,

Then return this parameter value callback ({...) in the background package. }), which passes the arguments to be returned in curly braces. Here is an example:

@RequestMapping (value= "/jsondo", produces = "application/json;charset=utf-8") public        @ResponseBody String Jsondo (String Tokenid, String callback) {   System.out.println ("Tokenid:" +tokenid); StringBuilder sb = new StringBuilder (); Sb.append (callback); Sb.append ("("); Sb.append ("{\" tokenid\ ": \" 111111111\ "}") ; Sb.append (")");        return sb.tostring ();              }  


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.