Analysis of Ajax cross-domain principle and implementation in jquery

Source: Internet
Author: User

The advent of AJAX enables Web pages to perform a partial refresh of a webpage by exchanging small amounts of data with the server in the background. However, for security reasons, Ajax does not allow cross-domain communication. If you try to request data from a different domain, an error occurs. These security errors can be avoided if you have control over the remote server where the data resides and each request goes to the same domain. But what is the use of WEB applications if you only stay on your own servers? What if you need to collect data from multiple third-party servers?

a thinking about the cross-domain of Ajax

  1. Why can't ajax cross-domain? Which part of the card is it? (The following item specifically says, here is the first conclusion). Ajax is actually sending a GET or POST request to the server and then getting the server response results back to the client. Cross-domain error is the location of the request to the data, not to get back, so our Ajax cross-domain problem can be translated into how the data back to the problem.

  2, since can not directly access the third-party site, we can do on the server proxy, through the Ajax to send a request to the agent, the agent to get the data back to the client, of course, this is a solution, but a request from the client through the agent to a third-party site, and then back to the original, the response speed is a problem

3, we found that we can put some JS, CSS and other files on the third party server, such as CDN to speed up the opening of the page, so there is no problem, that is, the Web page can be loaded in any site JS, CSS, pictures and other resources, will not be affected by the "cross-domain." This time, we will think: since we can call the third-party site JS, then if we put the data in the third-party site JS can not be able to bring data to the client?

Let's do an experiment to verify that our conjecture is not tenable:

Open Visual Studio, create a new Web project, use WebForm here, and then we add a JS file named Remotejs to the project and write the following code:

function Getremotedata () {    return "remote Data";}

Very simple, just a method, return a string, below we write a client call, since it is cross-domain, then write an HTML static page to test it, new local.html, enter the following code:

<!DOCTYPE HTML><HTML><Head>    <title>Local site</title>    <MetaCharSet= "UTF-8">    <Scripttype= "Text/javascript"src= "Http://localhost:4071/remoteJs.js"></Script></Head><Scripttype= "Text/javascript">    varData=Getremotedata (); alert (data);</Script><Body></Body></HTML>

Let our web project run up and then open local.html, you can see a popup window that shows the message remote data. This proves that our idea is correct. The next question is, how do we send requests and get the results of requests as needed? Now let's meet Jsonp.

Second, JSONP

1. What is Jsonp

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers. Its core idea is to use the cross-domain features inside the JS tag for cross-domain data access, in the JS tag there is a cross-domain URL, the actual execution time through this URL to obtain a string, the return string must be a valid JS call, Use the Eval string to complete the processing of the obtained data.

JSONP is an unofficial protocol that allows the server-side integration of script tags to return to the client, with the form of JavaScript callback for cross-domain access (this is just the JSONP simple implementation form).

2, the realization of JSONP

 Here's an example of how JSONP implements AJAX cross-domain requests. Here we mock the Library book query, in the Web project we have just built to add a general handler named Searchbook, write the following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;namespacebooklibrary{ Public classSearchbook:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; stringCallback = context. request["Callback"]; Context. Response.Write (Callback+"({' BookName ': ' 中文版 ', ' Pages ': 562})"); }         Public BOOLisreusable {Get            {                return false; }        }    }}

Temporarily do not explain, we finish the client to see the effect after the detailed description, and then modify just the local.html, the code is as follows:

<!DOCTYPE HTML><HTML><Head>    <title>Cross-Domain requests</title>    <MetaCharSet= "UTF-8"></Head><Body><inputtype= "button"value= "Send Request"onclick= "Getajaxdata ();" /></Body><Scripttype= "Text/javascript">    varGetData= function(data) {alert (data). BookName+ " " +data.   Pages);    }; functionGetajaxdata () {varURL= "Http://localhost:4071/SearchBook.ashx?callback=GetData"; varScript=Document.createelement ('Script'); Script.setattribute ('src', URL); document.getElementsByTagName ('Head')[0].appendchild (script); }   </Script></HTML>    

This HTML page has a button, binding method Getajaxdata, when we click Send Request, will send a request to the Web site, get the data of the query, we let the Web site run up, and then open local.html, click the button, see the following information pop-up:

We successfully obtained the data of the Web site and implemented cross-domain requests. Let's take a look at his implementation principle:

var url = "Http://localhost:4071/SearchBook.ashx?callback=GetData";

This line of code we define the URL of the request, before the question mark is the Web site general Handler Searchbook address, after the question mark we passed a parameter callback, the value is GetData, that is, we defined above the method name, and the callback function name. Of Course we can pass in more parameters.

var script = document.createelement (' script ');        Script.setattribute (' src ', url);        document.getElementsByTagName (

The three lines of code are to add the script node, the URL to the third-party site, the results

So what we've just written about the general handler returns the result of that, needless to say, he just returns a string that reads:

See here, it is the third-party site generates a call to the callback function, passing in the query results, and then executing through <script> loading to the client. See what's on your mind here? Does it have something in common with the delegates in C #? Overall process

Can see, the whole process, the local site has been active status, the initiative to send requests, the active loading of remote JS. Third-party sites are in a passive response.

3, the ordinary AJAX request in which link error

Below, we use jquery Ajax to illustrate what the AJAX request is stuck in, and modify the Getajaxdata method as follows:

           $.ajax ({                "get",                false,                "http://localhost:4071/ Searchbook.ashx ",                " text ",                function  (data) {                    +" "+  Data. Pages);                },                function  () {                    alert (' fail ');                }            });

Inside the Searchbook Context.Response.Write (callback + "({' bookname ': ' 中文版 ', ' Pages ': 562})"); This line of the lower point, and then run, will find that you can go to the breakpoint, And then it went wrong.

4. Using jquery to implement Ajax cross-domain

In fact, jquery also encapsulates the cross-domain AJAX approach, and let's look at how the above method is written in jquery:

<script type= "Text/javascript" >functionGetajaxdata () {$.ajax ({type:"Get", Async:false, URL:"Http://localhost:4071/SearchBook.ashx", DataType:"Jsonp", Jsonp:"Callback",//The name of the JSONP callback function that is passed to the request handler or page (typically: callback)Jsonpcallback: "GetData",//function Name of the callbackSuccessfunction(data) {alert (data). BookName+ " " +data.            Pages); }, Error:function() {alert (' Fail ');    }        }); }</script>

Note that jquery does not have to be written after the URL? To pass the parameter, the value of JSONP is equal to the value followed by the parameter name, and the Jsonpcallback value is the value.success of the argument is the method that is called after the successful execution.

Oh, no, no, how come there's no GetData method? How did jquery come true? Let's debug jquery and see how it's implemented, debug JS, and, of course, use Chrome to see the graph:

In this picture, we see that there is an object s, in doing the URL splicing operation, see the selected line,? The back of the spell is S.JSONP, and finally stitching is callbackname. Continue down:

We see the value of the S.url, for the value after stitching, is not the same as we wrote the JS code inside the same URL, continue to go down:

We see jquery Adding an underscore sign after the URL just followed by a string of numbers, and as for what, I can't say, go down:

See what, success method, Haha, this is jquery in variable parameters, continue to walk:

What did you see? Yes, that's the way jquery is finally called, the last line of code, the script node added, and the same principle I wrote for my own JS implementation. Keep going down and see what else you have:

When you see jquery executing, you delete the script node you just added, or jquery is thoughtful.

Let's take a look at the DOM structure we wrote on our own after JS execution:

See, the script node will soar along with the number of requests, but it will not cause errors and will disappear after the refresh. When jquery executes, the DOM structure is unchanged.

Iii. Summary

1, Ajax and JSONP the two technologies in the invocation of the way "looks" very much like, the purpose is the same, is to request a URL, and then the server to return the data processed, so the jquery and ext and other frameworks have Jsonp as a form of Ajax encapsulation;

2, Ajax and JSONP are essentially different things. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is to dynamically add <script> tags via HTTP to invoke the JS script provided by the server.

3, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.

4, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.

5, Jsonp the whole process, the local site has been active status, the initiative to send the request, the active loading of remote JS. Third-party sites are in a passive response.

Cloud drizzling

QQ Exchange Group: 243633526

Blog Address: http://www.cnblogs.com/yunfeifei/

Disclaimer: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and my unit does not have a direct interest in the relationship. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.

If you feel that my blog is helpful to everyone, please recommend supporting one, give me the motivation to write.

Analysis of Ajax cross-domain principle and implementation in jquery

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.