Cross-domain JSONP principle and invocation detailed demo sample

Source: Internet
Author: User
Tags script tag

The previous blog describes the same-origin and cross-domain access concepts, which refer to the basic ways of using cross-domain frequently: Jsonp and cors.

Then this blog will introduce Jsonp way.

Jsonp principle under the same-Origin policy, a page under a server cannot get data outside of the server, but the tags such as IMG, IFRAME, script, and so on are exceptions.  These tags are able to request data on other servers through the SRC attribute.  The JSONP is called cross-domain requests through the script node src.  When we request cross-domain resources through the JSONP mode, the server returns a piece of JavaScript code to the client, which itself invokes the client callback function itself. give a sample clienthttp://localhost:8080 visit Serverhttp://localhost:11111/user. Under normal circumstances, this is not agreeable.

Because these two URLs are of different domains.

What if we use the JSONP format to send requests? Http://localhost:11111/user?

Callback=callbackfunction the data returned by the server such as the following: Callbackfunction ({"id": 1, "name": "Test"}) take a careful look at the data returned by the server, is actually a piece of JavaScript code.  This is the function name (parameter) format.  When the server returns, it runs the Callbackfunction function on its own initiative. Therefore, the client needs to callbackfunction the function. To use JSONP mode to return JavaScript code and run its callback function on its own initiative.
Note: The callback and callbackfunction in the URL address are arbitrarily named.

detailed JS implementation Jsonp code.

JS in:

  <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 Functions function callbackfunction (data) {var html=json.stringify (data). RESULTSET); alert (HTML); } </script>

Server code action: The callback function is required to wrap outside the JSON returned by the background. The detailed methods are 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 ();p arammap.put ("Bank_no", 100+i); Parammap.put ("Money_type", i);p arammap.put ("Bank_name", i);p arammap.put ("Bank_type", i);p arammap.put ("Bank_status ", 0);p arammap.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 the JSONP code.

jquery starts with the 1.2 version and supports the implementation of JSONP.

$ (function () {     Jquery.getjson ("http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=?", function (data) {   var html=json.stringify (data. RESULTSET); $ ("#testjsonp"). HTML (HTML);}     ); });
The first one? The representation is followed by the number of references, as we call it in general. What's important is the second one? jquery dynamically gives you the name of the destroyed function.
As for the background code and the same above, use the same background.


Ajax implements JSONP code in jquery.

     $.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 number of references is callback, not the other.    The Calback value in the action code is String cb=request.getparameter ("callback");    and the resulting callback function, by default, is similar to a large number of these. Based on the AJAX manual. Change the callback name and the callback function name.

Http://www.w3school.com.cn/jquery/ajax_ajax.asp Jsonp:jsonp, the requested address is:

jsonp=%e8%87%aa%e5%8a%a8%e7%94%9f%e6%88%90%e5%9b%9e%e8%b0%83%e5%87%bd%e6%95%b0%e5%90%8d ">http://localhost : 8080/crcp/rcp/t99eidt/testjson.do?

Jsonp= self-generated callback function name Jsonpcallback:callbackfunction, the requested address is: Http://localhost:8080/crcp/rcp/t99eidt/testjson.do?

Jsonp=callbackfunction last returned to the foreground is: callbackfunction (detailed JSON value)
Among the above JS implementation JSONP code. Instead of dynamically stitching script scripts, write script tags directly. such as the following: <script type= "Text/javascript" src= "" ></script> if so, through debug found, indeed returned correctly. However, the callback function was not found. Even if JS also provides a callback function "Each browser is tested" to be displayed via JS. Create the script tag dynamically through the code.
JSONP cross-domain mode.   Very convenient, also support the majority of the browser at the same time, but the only disadvantage is that only the get Submit method, not support other post submissions. If the URL address transfer too many, how to implement it? The next blog will explain there is a cross-domain scenario Cros principle and a detailed invocation demo sample.

Cross-domain JSONP principle and invocation detailed demo sample

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.