Jsonp break through the same-origin policy for cross-domain access requests

Source: Internet
Author: User
Tags domain server

Cross-domain access issues, I believe everyone has encountered. This is a very tricky question. But however persuasive, outsmart, there is always a solution to this kind of problem. Recently I have come into contact with this problem, the solution is AJAX+JSONP.


Speaking of this problem, we have to say " homologous Strategy", which is a famous security policy proposed by Netscape.Same-origin. This policy is now used by all JavaScript-enabled browsers. The so-called homologous, it is necessary agreement, domain name, port are consistent, is called homologous. For example: http://www.12306.cn and https://www.12306.cn, because the protocol is inconsistent, it is not homologous. Http://127.0.0.1:8080/test1 and Http://localhost:8080/test1 also do not belong to the same origin, because the domain name is inconsistent. The port is different, of course, is not called homologous.


in the case of non-homologous, when requesting data, the browser will report an exception in the console prompting for access denied. This is a very painful problem for web developers. For example, I now open the Baidu Web page, and then in the console Request CSDN Web page, then the exception will be reported:



in this, you may see the word "Access-control-allow-origin", which is a technique proposed by the standard to solve cross-domain problems caused by homologous strategies-" cross-domain resource sharing (cors,cross-origin Resource sharing) ". As long as you set this access-control-allow-origin header on the server, you can allow cross-domain access. If you are interested, check it yourself, it is very simple. However, it has security implications , primarily because of the support for wildcards *. Every website can be requested at will, it is too insecure. such as:

Response.setheader ("Access-control-allow-origin", "*");

The get method of $.ajax in query is supported for cross-domain access, but datatype is set to "Jsonp". JSONP (JSON with Padding) is a "usage pattern" of JSON that allows Web pages to get data from other domains. JSONP is implemented by using the JS callback mechanism. the way to use it is also simple, the code is as follows:

$.ajax ({  URL: ' http://localhost:8080/test2/searchJSONResult.action ',  type: ' GET ',  dataType: ' Jsonp ',  data: {name: "Zhanghuihua"}, timeout:5000,  success:function (JSON) {    //client jquery pre-defined callback function, Once the JSON data on the cross-domain server is successfully obtained, the callback function    alert (JSON) is executed dynamically,  and  error:function () {    alert ("Request failed! ");   }});/ /The simple way is as follows: $.getjson ("http://localhost:8080/test2/searchJSONResult.action?name1=ZhangHuihua&jsoncallback=?", function (JSON) {//execute code});

on the server side, re-stitch the JSON data:

/** gets the individual parameters of the request (user name, etc.) **/map Map = Request.getparametermap ();/** gets JSONP callback function name **/string callback = Request.getparameter (" Callback ");/** calls the business logic and translates the results into JSON format **/string msg = Convert2json (Services.login (map))/** re-stitching the format and outputting  **/ OUT.PRINTLN (callback + "(' + msg + ')");

This allows the browser to retrieve the JSON data returned from the source server. This return is not the same as the JSON format, which is formatted as a callback function name + (JSON array). Where the parentheses cannot be omitted. Otherwise the request was sent successfully, but the data was not obtained because the returned data format was wrong. as follows:



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.