This article describes how JSONP cross-origin is implemented and discusses the principles of JSONP cross-origin. The JSONP cross-origin GET request is used to solve the problem of Ajax cross-origin access. You can refer to a new requirement in the next few days. You need to call the backend Webservice method to return information asynchronously on the front-end web page. There are many implementation methods. In this example, jQuery + Ajax is used. After the process is completed, all the OK codes are debugged locally, but problems occur after being deployed to the server, and no response is returned for backend service calls, what's going on? The Code has not been changed. The only modification is the url address in jQuery's ajax method. Is it the problem here? After checking and debugging, it turns out that the same-origin policy is playing a strange role. We know that JavaScript or jQuery is a dynamic script technology that is often used in front-end Web development. In JavaScript, there is a very important security restriction, called "Same-Origin Policy" (Same-Origin Policy ). This Policy imposes significant limitations on the page content that JavaScript code can access, that is, JavaScript can only access the content under the same domain name as the document or script that contains it. Scripts under different domain names cannot access each other, even subdomains. For more details about the same-origin policy, Baidu will not go into details here.
But sometimes cross-origin operations are inevitable. At this time, the "same-origin policy" is a restriction. What should I do? Using JSONP cross-origin GET requests is a common solution. Let's take a look at how JSONP cross-origin is implemented and discuss the principles of JSONP cross-origin.
If JSONP is mentioned here, someone will ask, what are the differences and differences between JSONP and JSON? Next, let's take a look. Baidu Baike has the following descriptions:
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language. Easy for reading and writing, and easy for machine resolution and generation (fast network transmission ).
JSONP (JSON with Padding) is a "usage mode" of JSON, which can be used to solve cross-Origin data access problems in mainstream browsers. Because of the same-origin policy, web pages located in server1.example.com cannot communicate with servers that are not server1.example.com, And the HTML script element is an exception. Using this open policy of the script element, webpages can obtain JSON data dynamically generated from other sources. This usage mode is called JSONP. The information captured with JSONP is not JSON, but arbitrary JavaScript. It is executed with a JavaScript literal interpreter instead of a JSON parser.
Here, we should understand that JSON is a lightweight data exchange format, like xml, used to describe data. JSONP is a method that uses JSON data. It returns a javaScript script that contains a JSON object instead of a JSON object.
How does JSONP work? We know that, due to the restrictions of the same source policy, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. Cross-origin requests cannot be used for security reasons. However, we find that the js file called on the Web page is not affected by cross-origin, tags with the "src" attribute all have cross-domain capabilities, such as script,At this time, the clever programmer comes up with a work ing method. If you want to make a cross-origin request, use the html script tag for cross-origin requests, return the script code to be executed in the response, where javascript objects can be directly transmitted using JSON. That is to say, if JSON data is generated on the Cross-origin server and then packaged as a script for returning the data, it will not break through the restrictions of the same-origin policy. Does it solve the problem of cross-origin access. </P> <p> let's take a look at how to implement it: </p> <p> front-end code: </p> <p class = "codetitle"> <U> </U> the code is as follows: </p> <p class = "codebody" id = "code59757"> <br/> function CallWebServiceByJsonp () {<br/>$ ("# SubEquipmentDetails" ).html (''); <br/> $. ajax ({<br/> type: "GET", <br/> cache: false, <br/> url :" http://servername/webservice/webservice.asmx/GetSingleInfo ", <Br/> data: {strCparent: $ (" # Equipment_ID "). val () },< br/> dataType: "jsonp", <br/> // jsonp: "callback", <br/> jsonpCallback: "ongetmembersuccpolicyjsonp" <br/>}); <br/>}< br/> function ongetmembersuccpolicyjsonp (data) {<br/> // process data <br/> alert (data ); <br/>}< br/> </p> <p> backend WebService code: </p> <p class = "codetitle"> <U> </U> the code is as follows: </p> <p class = "codebody" id = "code51471"> <br/> [WebMethod] <br/> [ScriptMethod (ResponseFormat = ResponseFormat. json, UseHttpGet = true)] <br/> public void GetSingleInfo (string strCparent) <br/>{< br/> string ret = string. empty; <br/> HttpContext. current. response. contentType = "application/json; charset = UTF-8"; <br/> string jsonCallBackFunName = HttpContext. current. request. params ["callback"]. toString (); <br/> // string jsonCallBackFunName1 = HttpContext. current. requ Est. queryString ["callback"]. trim (); <br/> // The code above must be <br/> // The intermediate code executes its own business operations and can return any information of itself (multiple data types) <br/> BLL. equipment eq_bll = new BLL. equipment (); <br/> List <Model. equipment> equipmentList = new List <Model. equipment> (); <br/> equipmentList = eq_bll.GetModelEquimentList (strCparent); <br/> ret = JsonConvert. serializeObject (equipmentList); <br/> // the following code must be <br/> HttpContext. current. response. write (string. form At ("{0} ({1})", jsonCallBackFunName, ret); <br/> HttpContext. current. response. end (); <br/>}< br/> </p> <p> As shown above, the front-end CallWebServiceByJsonp method uses jQuery's ajax method to call the backend Web Service's GetSingleInfo method, the backend's GetSingleInfo method, and the front-end's callback method ongetmembersuccpolicyjsonp to wrap the JSON object of backend business, return a javascript snippet to the front end for execution. It cleverly solves the problem of cross-origin access. </P> <p> disadvantages of JSONP: </p> <p> JSONP does not provide error handling. If the dynamically inserted code runs normally, you can get a response, but if it fails, nothing will happen. </P> <p> Are you familiar with solving Ajax cross-origin access problems in JSONP cross-origin GET requests? The idea of this article is very good and I recommend it to you.