Cross-origin JSONP principle and call examples

Source: Internet
Author: User

The previous blog introduced the same-origin policy and the concept of cross-origin access, which mentioned common cross-origin Methods: JSONP and CORS. This blog introduces the JSONP method.JSONP PrincipleIn the same-origin policy, data outside the server cannot be obtained on a page under a server, but labels such as img, iframe, and script are exceptions, these tags can request data from other servers through the src attribute. JSONP is a cross-origin request called through the script node src. When we request cross-origin resources in JSONP mode, the server returns a piece of javascript code to the client, which automatically calls the client callback function.For exampleClient http: // localhost: 8080 Access Server http: // localhost: 11111/user. Normally, this is not allowed. Because these two URLs belong to different domains. What if we send a request in JSONP format? Http: // localhost: 11111/user? Callback = callbackfunction the data returned by the server is as follows: callbackfunction ({"id": 1, "name": "test"}). Check the data returned by the server carefully. It is actually a piece of javascript code, this is the format of the function name (parameter. After the server returns, the callbackfunction is automatically executed. Therefore, the client needs the callbackfunction function to automatically execute the callback function after returning javascript code in JSONP mode.
Note: callback and callbackfunction in the url are randomly named.The specific JS implementation JSONP code.JS:

<Script> var url = "http: // localhost: 8080/crcp/rcp/t99eidt/testjson. do? Jsonp = callbackfunction "; var script = document. createElement ('script'); script. setAttribute ('src', url); // load javascript document. getElementsByTagName ('head') [0]. appendChild (script); // callback function callbackfunction (data) {var html = JSON. stringify (data. RESULTSET); alert (html) ;}</script>
Server code Action: The json returned by the background must be wrapped by the callback function. The specific method is as follows:
public class TestJson extends ActionSupport{@Overridepublic String execute() throws Exception {try {JSONObject jsonObject=new JSONObject();List list=new ArrayList();for(int i=0;i<4;i++){Map paramMap=new HashMap();paramMap.put("bank_no", 100+i);paramMap.put("money_type", i);paramMap.put("bank_name", i);paramMap.put("bank_type", i);paramMap.put("bank_status", 0);paramMap.put("en_sign_ways", 1);list.add(paramMap);}JSONArray rows=JSONArray.fromObject(list);jsonObject.put("RESULTSET", rows);HttpServletRequest request=ServletActionContext.getRequest();HttpServletResponse response=ServletActionContext.getResponse();response.setContentType("text/javascript");boolean jsonP = false;String cb = request.getParameter("jsonp");if (cb != null) {    jsonP = true;    System.out.println("jsonp");    response.setContentType("text/javascript");} else {System.out.println("json");    response.setContentType("application/x-json");}response.setCharacterEncoding("UTF-8");Writer out = response.getWriter();if (jsonP) {    out.write(cb + "("+jsonObject.toString()+")");    System.out.println(jsonObject.toString());}else{out.write(jsonObject.toString()); System.out.println(jsonObject.toString());}} catch (Exception e) {e.printStackTrace();}       return null;}}
  JQUERY implements JSONP code.Jquery also supports JSONP implementation since version 1.2.
$(function(){     jQuery.getJSON("http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=?",function(data){   var html=JSON.stringify(data.RESULTSET);$("#testjsonp").html(html);}     ); });
First? It indicates that the parameter is followed, which is the same as the common call. What's important is the second one ?, Jquery dynamically generates the destroy function name for you.
As for the same background code as above, the same background is used.
In JQUERY, Ajax implements JSONP code.
     $.ajax({    type:"GET",    async :false,    url:"http://localhost:8080/crcp/rcp/t99eidt/testjson.do",    dataType:"jsonp",    success:function(data){    var html=JSON.stringify(data.RESULTSET);    $("#testjsonp").html(html);    },    error:function(){    alert("error");    }       });
Note: In this form, the default parameter is callback, rather than other parameters. If the calback value is obtained in the action code, the String cb = request. getParameter ("callback") and the generated callback function are similar to the preceding one by default. Modify the callback name and callback function name according to the Ajax manual. Http://www.w3school.com.cn/jquery/ajax_ajax.asp jsonp: jsonp, then the request address is: http: // localhost: 8080/crcp/rcp/t99eidt/testjson. do? Jsonp = the callback function name jsonpCallback: callbackfunction is automatically generated. The request address is http: // localhost: 8080/crcp/rcp/t99eidt/testjson. do? Jsonp = callbackfunction: callbackfunction (json value) is returned at the end)
In the above JS Implementation of JSONP code, if you do not dynamically splice the script, but directly write the script tag, similar to the following: <script type = "text/javascript" src = ""> </script> if this is the case, debug finds that the callback function is returned correctly, but always prompts that the callback function cannot be found. Even if js also provides a callback function [all browsers are tested] to be displayed through JS, the code dynamically creates the script tag.
The JSONP cross-origin method is convenient and supports most browsers. However, the only drawback is that only the GET submission method is supported and other POST submission methods are not supported. If there are too many parameters transmitted by the url address, how can this problem be achieved? The next blog will explain the CROS principle of another cross-origin solution and the specific call example.

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.