Analysis on JSONP-solving cross-origin Ajax access, jsonp-ajax

Source: Internet
Author: User
Tags clever programmer

Analysis on JSONP-solving cross-origin Ajax access, jsonp-ajax

Analysis on JSONP-solving Ajax cross-origin access problems

 

I haven't written anything for a long time. I always feel that I don't have time. Actually, time is... To put it bluntly, there was a new demand for work a few days ago, and the front-end web page needs to asynchronously call the backend Webservice method to return information. 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 solutionNext, 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 in server1.example.com, And the <script> element of HTML is an exception. Using the open policy of the <script> element, the webpage 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>, , and <iframe>. At this time, A clever programmer comes up with a work ing method. If you want to make a cross-origin request, use the html script tag to perform the cross-origin request and return the script code to be executed in the response, the javascript object 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.

Let's take a look at how to implement it:

Front-end code:

Function CallWebServiceByJsonp () {$ ("# SubEquipmentDetails" ..html (''); $. ajax ({type: "GET", cache: false, url: "http: // servername/webservice. asmx/GetSingleInfo ", data: {strCparent: $ (" # Equipment_ID "). val ()}, dataType: "jsonp", // jsonp: "callback", jsonpCallback: "ongetmembersuccpolicyjsonp"});} function ongetmembersuccpolicyjsonp (data) {// process data alert (data );}

 

Backend WebService code:

[WebMethod] [ScriptMethod (ResponseFormat = ResponseFormat. json, UseHttpGet = true)] public void GetSingleInfo (string strCparent) {string ret = string. empty; HttpContext. current. response. contentType = "application/json; charset = UTF-8"; string jsonCallBackFunName = HttpContext. current. request. params ["callback"]. toString (); // string jsonCallBackFunName1 = HttpContext. current. request. queryString ["callback"]. trim (); // The code above must be // The intermediate code executes its own business operations and can return any information of its own (multiple data types) BLL. equipment eq_bll = new BLL. equipment (); List <Model. equipment> equipmentList = new List <Model. equipment> (); equipmentList = eq_bll.GetModelEquimentList (strCparent); ret = JsonConvert. serializeObject (equipmentList); // the following code must be HttpContext. current. response. write (string. format ("{0} ({1})", jsonCallBackFunName, ret); HttpContext. current. response. end ();}

 

As shown above, the front-end CallWebServiceByJsonp method uses jQuery's ajax method to call the backend Web Service GetSingleInfo method, the backend GetSingleInfo method, and the front-end callback method ongetmembersuccpolicyjsonp to package the JSON object for back, return a javascript snippet to the front end for execution. It cleverly solves the problem of cross-origin access.

 

Disadvantages of JSONP:

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.

 

Related Article

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.