Brief analysis on jsonp-solving Ajax cross-domain access problem

Source: Internet
Author: User
Tags script tag

Brief analysis on jsonp-solving Ajax cross-domain access problem

For a long time did not write essays, always feel no time, in fact, the timing is ... Needless to say, a few days ago, there is a new need for work, the front-end Web page needs to invoke the backend WebService method return information. There are a variety of implementation methods, this example uses Jquery+ajax, after the completion of the local debugging everything OK, but the deployment to the server after the problem, the background service calls are not responding, what is going on? The code doesn't change much, and the only thing that changes is the URL address in jquery's Ajax method. Is it the problem here, after checking and debugging, to discover that the original is a homologous strategy in mischief, we know that JavaScript or jquery is a dynamic scripting technique that is often used in web front-end development. In JavaScript, there is a very important security restriction called "Same-origin policy" (same-origin strategy). This strategy is an important restriction on the page content that JavaScript code can access, meaning that JavaScript can only access content that is under the same domain name as the document or script that contains it. Scripts under different domain names do not have access to each other, even subdomains. About the same-origin strategy, the reader can Baidu more detailed explanation, here no longer repeat.

But sometimes it is unavoidable to cross-domain operation, when the "homologous strategy" is a limitation, how to do? using JSONP cross-domain get Requests is a common solution , let's take a look at how Jsonp cross-domain is implemented, and explore the principle of the next Jsonp cross-domain.

Here refers to the JSONP, then someone asked, it is different from JSON and differences, and then we will take a look, Baidu encyclopedia has the following instructions:

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript (standard ECMA-262 3rd edition-december 1999). JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and build (network transfer speed).

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers. Because of the same-origin policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, while HTML <script> elements are an exception. Using this open strategy of <script>, the Web page can get JSON data that is dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser.

Here, it should be understood that JSON is a lightweight data interchange format that, like XML, is used to describe between data. Jsonp is a way to use JSON data, not a JSON object, but a JavaScript script that contains JSON objects.

How does that JSONP work? We know that, due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). It is not possible to cross-domain requests for security reasons, but we find that the JS file on the Web page is not affected by the cross-domain, and that the label with the attribute "src" has cross-domain capabilities such as <script>, , < Iframe> At this time, the clever program ape thought of the workaround, if you want to cross-domain requests, cross-domain requests by using the HTML script tag, and return the script code to execute in the response, which can be passed directly using JSON JavaScript object. That is, in the cross-domain of the server to generate JSON data, and then packaged into script scripts back, do not break through the same-origin policy restrictions, solve the problem of cross-domain access.

Let's see how it's going to be achieved:

Front-End Code:

function Callwebservicebyjsonp () {        $ ("#SubEquipmentDetails"). html (');        $.ajax ({            type: "GET",            cache:false,            URL: "Http://servername/webservice/webservice.asmx/GetSingleInfo" ,            data: {strcparent: $ ("#Equipment_ID"). Val ()},            DataType: "Jsonp",            //jsonp: "Callback",            Jsonpcallback: "Ongetmembersuccessbyjsonp"        }); function Ongetmembersuccessbyjsonp (data) {    //Processing Data    alert (data);}

WebService code for the backend:

        [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 above code must//intermediate code to perform its own business operations, can return any of its own information (majority data type) 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 Callwebservicebyjsonp method of the front end uses the Ajax method of jquery to invoke the backend Web service Getsingleinfo method, the Getsingleinfo method of the back end, Use the callback method of the front end to ONGETMEMBERSUCCESSBYJSONP a JSON object that wraps the business operations of the background, and returns to the front end a piece of JavaScript fragment execution. A clever solution to cross-domain access issues.

Disadvantages of Jsonp:

JSONP does not provide error handling. If the dynamically inserted code runs correctly, you can get back, but if it fails, nothing will happen.

Brief analysis on jsonp-solving Ajax cross-domain access problem

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.