JS Note Note (--JSONP) actually very simple "Ajax cross-domain Request"

Source: Internet
Author: User
Tags file url domain server

Two days ago was asked how Ajax cross-domain how to solve, and really was asked to live, the light know what jsonp, vaguely did not say up. Holding a problem must be resolved attitude, I read a lot of information, so ...

Why do you always know Jsonp, but have been vaguely confused? --The information on the Internet is too complex to write about!

I can be as simple as how simple, and strive to let you read 10 minutes!

1. Same-origin strategy

The reason why Ajax needs "cross-domain" is the browser's homologous strategy. That is, the Ajax of a page can only get data from the same source or the same domain as the page.

How to call "homology" or "Same domain"? --The protocol, domain name, and port number must be the same . For example:

Http://google.com and https://google.com are different, because the agreement is different;

http://localhost:8080 and http://localhost:1000 are different because the ports are different;

http://localhost:8080 and https://google.com different, the agreement, domain name, port number are different, is not a family at all.

According to the same-origin strategy, I made a Web page http://localhost:8080/test.html can not directly get http://google.com data through Ajax.

For example, I use AJAX to access a page of a different domain, and the error results are:

If you think about it, it makes sense. If there is no homologous policy, you and I can freely through the Ajax direct access to other Web site information, this is not a mess ... I do a search interface, search directly with Ajax from Baidu to obtain data, it is not a thief ...

But cross-domain access is unavoidable, mail.163.com Web pages may need to get news information from the news.163.com domain, what should I do? -- Start our cross-domain journey. (can also be achieved with an IFRAME, of course)

2. Starting with the word "hotlinking"

The internet of many sites between the pictures of each other hotlinking, a site page of the IMG.SRC directly linked to the B site image address, this is often the matter. When it comes to "hotlinking", the first thing we think about is how to prevent hotlinking, we don't care about that.

What do you think of the two words "hotlinking" and "homologous strategy"? --Yes, contradiction! since all "homologous strategy", how can Still "hotlinking"?

All things in the world have contradictions, there are contradictions can still coexist harmoniously, and do not necessarily have to kill.

Focus: src(get picture),<link> href(get css),<script> src (Get JavaScript) None of the three are compliant with the same Origin policy , and they can get data across domains. So you can get jquery directly from some CDN, and the pictures on your site can be stolen by others at any time, all with the best watermark!

And our protagonist today-jsonp--is because <script> 's SRC does not conform to the homologous strategy .

3. JSONP

For example, there is a a.com/test.html page under the domain name A.com, and a b.com/data.html page and b.com/alert.js file under the domain name B.Com.

Boot First step: simple reference JS

Write B.com/alert.js as follows:

alert (123);

Write the following code for a.com/test.html:

<typesrc= ' http://b.com/alert.js '/>

Running a.com/test.html, the result is obvious, is to pop up "123".

Guided second step: reference JS return data

Modify the B.com/alert.js to:

MYFN (100);

Modify the a.com/test.html to:

<Script>    functionMYFN (data) {alert ( data+ 'px' ); }</Script><Scripttype= ' Text/javascript 'src= ' Http://b.com/alert.js '/>

Run a.com/test.html, the result is pop "100px", this should also have no doubt.

Boot step three: already cross-domain success!

In the second step , if data--is 100--is a data I want to cross-domain under B.Com, then we have already implemented cross-domain request!!!

Make this process clear again:

    • <script> SRC does not conform to homologous strategy;
    • I assign a cross-domain file URL (perhaps not a JS file) to <script> src, and the string returned by the file will be parsed by the browser as JavaScript;
    • And in this JavaScript, it can contain the data that I need to cross-domain server side;
    • Finally, I define a MYFN function on this page to show the data, and in this javascript you can call the MYFN function directly;

Boot Fourth step: referencing HTML format

<script> SRC does not necessarily point to JavaScript files, it can point to any address. For example:

Modify the a.com/test.html to:

<Script>    functionMYFN (data) {alert ( data+ 'px' ); }</Script><Scripttype= ' Text/javascript 'src= ' http://b.com/data.html '/>

Write b.com/data.html as: (note that the following line of code is written in the data.html, many do not write)

Running a.com/test.html, the result is still "100px"

Of these, "100" is the data we want to request across domains.

Guided Fifth step: Dynamic Data

If the data you want to request is dynamic, write it in a dynamic page.

So let's get a.com/test.html to invoke a dynamic ASPX page:

<Script>    functionMYFN (data) {alert ( data+ 'px' ); }</Script><Scripttype= ' Text/javascript 'src= ' Http://b.com/data.aspx?callback=myFn '/>

Note that we added "? callback=myfn" to the SRC address, meaning The function of displaying the data is also passed on dynamically. , and the second and fourth steps are statically written in the called file.

As for the callback parameter background how to receive, how to use, please continue to look:

Under B.Com Add a b.com/data.aspx page, the background code is as follows:

    protected voidPage_Load (Objectsender, EventArgs e) {        if( This. IsPostBack = =false)        {            stringcallback =""; if(request["Callback"] !=NULL) {Callback= request["Callback"]; //data to be returned by the server side                stringdata ="1024x768"; Response.Write (Callback+"("+ Data +")"); }        }    }

The code is simple, gets the callback parameter, and then forms a function to return. If "B.COM/DATA.ASPX?CALLBACK=MYFN" is called, then the return is "MYFN (1024)".

The returned data becomes dynamic ("1024"), and the function that the front page uses to display the data is also programmed dynamically ("Callback=myfn"), but in the final analysis, the form is the same.

Boot Sixth step: Call encapsulation

A.com/test.html, there is only one <script> lying there quietly, after the execution once, there is no effect.

The reality is that, in a.com/test.html, a number of calls may occur with the user's actions. What to do? --Dynamic increase chant.

function Addscripttag (src) {    var script = document.createelement ("script");    Script.setattribute ("type", "Text/javascript");     = src;    Document.body.appendChild (script);} function MYFN (data) {    + ' px ');  } // When you need to adjust: // addscripttag (' b.com/data.aspx?callback=myfn ');

4. Summary

The above layer describes the JSONP, you do not have to remember its definition, see the above words, the almighty understanding.

The point is: the same origin strategy + <script> SRC does not belong to the same origin policy + the file returned by the SRC point of <script> returns the server-side data .

OK, that's all!

-------------------------------------------------------------------------------------------------------------

Please pay attention to my Weibo.

Also welcome to follow my other tutorials:

"From design to pattern" "In-depth understanding JavaScript prototype and Closure series "" Microsoft petshop4.0 Source Interpretation video" "json2.js source interpretation Video"

JS Note Note (--JSONP) actually very simple "Ajax cross-domain Request"

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.