An analysis of JSONP solution to the problem of Ajax cross-domain access _ajax related

Source: Internet
Author: User
Tags error handling httpcontext script tag domain server

A few days ago, there was a new need for a front-end Web page to invoke the backend WebService method return information asynchronously. Implementation of a variety of methods, this example using Jquery+ajax, completed, debugging in the local all OK, but deployed to the server after the problem, the background service call does not respond, how? The code doesn't change much, the only thing that changes is the URL address in the Ajax method of jquery. Is the problem here, after checking and debugging, to discover that the original homology strategy is at work, and 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 limitation, known as the "Same-origin Policy" (Homology policy). This policy makes a significant restriction on the content of the page that JavaScript code can access, that is, 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 are not accessible to each other, even to subdomains.

But sometimes it is inevitable that you need to do cross-domain operations, when the "homology strategy" is a limitation, how to do? Using JSONP cross domain Get Requests is a common solution, let's take a look at how the JSONP Cross-domain is implemented, and explore the principle of the jsonp across domains.

Here mentioned the JSONP, that someone asked, it and JSON what is the difference and difference, 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 uses a completely language-independent text format, but it also uses a family of C-language (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy for people to read and write, but also easy to machine parsing and generation (network transmission speed).

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to solve the problem of Cross-domain data access for mainstream browsers. Because of the homology 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 policy of <script> elements, Web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP. The data captured by JSONP is not JSON, but arbitrary JavaScript, executed using a JavaScript literal instead of parsing with the JSON parser.

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

So how does JSONP work, we know that because of the restriction of homology policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port). Cross-domain requests are not possible for security reasons, but we find that when you call a JS file on a Web page, it is not affected by cross-domain, and tags with the attribute "src" have cross-domain capabilities, such as <script>, , < Iframe> At this time, the clever program ape came up with a workaround, and if you want to make Cross-domain requests, cross domain requests by using the HTML script tag, and return the script code to execute in the response, where you can pass directly using JSON A JavaScript object. That is, generating JSON data on a cross-domain server, and then wrapping it back up as script scripts, which does not break the restrictions of the homologous policy and solves the problem of Cross-domain access.

Here we will see how to achieve:

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 at back end:

 [WebMethod] [Scriptmethod (Responseformat = Responseformat.json, Usehttpget = True)] Publi c 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 information of its own (majority 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 jquery Ajax method to invoke the backend Web service Getsingleinfo method, the backend Getsingleinfo method, Use the front-end callback method to ONGETMEMBERSUCCESSBYJSONP the JSON object that wraps the business operation in the background, and return it to the front-end JavaScript fragment execution. The problem of Cross-domain access is solved skillfully.

Disadvantages of Jsonp:

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

The above content simple to introduce the JSONP to solve the problem of Ajax Cross-domain access to the idea, I hope to help everyone, if you have questions welcome to my message, small series will promptly reply to everyone, here also thank you for the cloud Habitat Community website support!

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.