On the principle and application of JavaScript cross-domain and JSONP

Source: Internet
Author: User
Tags script tag set time domain server

The same-origin strategy, a well-known security policy presented by Netscape, is now used by all JavaScript-capable browsers.

Why a homologous strategy is required, here is an example:

Suppose there is no homologous strategy now, what will happen? As you know, JavaScript can do a lot of things, like reading/Modifying a value in a webpage. Well, now that you've opened the browser, opened the bank Website in a tab window, opened a malicious website in another tab window, and that malicious website hangs a JavaScript that specifically modifies the bank information, when you visit this malicious website and execute it javascript, Your bank page will be modified by this JavaScript, the consequences will be very serious! And the homologous strategy is to prevent this from happening.

For example, Http://www.baidu.com/index is opened in the browser's two tab pages, respectively. HTML and http://www.google.com/index.html, where JavaScript1 and JAVASCRIPT3 belong to the Baidu script, and JavaScript2 is a Google script, When the browser's tab1 to run a script, it will be the same origin check, only and www.baidu.com homologous script can be executed, so-called homologous, refers to the domain name, protocol, the same port. Therefore, TAB1 can only execute JavaScript1 and JAVASCRIPT3 scripts, and JavaScript2 cannot execute, thus preventing illegal tampering of this webpage by other Web pages.

Second, what is JSONP?
JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client, via JavaScript callback, for cross-domain access (this is just Jsonp simple Implementation form).

Third, why use JSONP?
Because JSON is just plain text with a simple parenthesis structure, many channels can exchange JSON messages. Because of the limitations of the same-origin policy, we cannot use XMLHttpRequest when communicating with external servers. Jsonp is a way to bypass the same-origin strategy by using JSON with the < script> tag to directly return executable JavaScript function calls or JavaScript objects from the server.

In fact, JSONP is a very simple thing. The main use of <script/> tags on javascript document dynamic parsing to achieve. (You can actually use the Eval function as well).

<script type= "Text/javascript" > function jsonpcallback (Result) {alert (result.msg); }</script><script type= "Text/javascript" src= "http://crossdomain.com/jsonServerResponse?jsonp= Jsonpcallback "></script>

Where Jsoncallback is a function that is registered by the client and gets the JSON data on the cross-domain server after the callback.

Http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback

This URL is the interface of the cross-domain server to fetch JSON data, the parameter is the name of the callback function, the return format is:

Jsonpcallback ({msg: ' This is JSON data '})

Jsonp principle:

First register a callback with the client and then pass the callback name to the server. At this point, the server becomes JSON data. Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function).

In fact, that is, the client defines a function (such as a), the server-side return after the request address is called a function, the required data is placed in the parameters of a function.

Demo

It should be used only as a simple script element in all HTML elements. Do you think it's more strange to see this? It doesn't matter, continue to see will be the latrine (stuffed) Open, hehe ~ To see an example:
Demo.html:

<! DOCTYPE html>

Demo.js:

Say ("Hello, everyone!");

After running the demo.html file, do you see "Hello, everyone!" written? Warning box? You might think this example is simple, nothing great, or even wondering: does it have anything to do with JSONP? Well, I can be sure to tell you: there is a relationship! Moreover, this example is actually a prototype of JSONP! You might think that JSONP is not accessing remote data? Yes, imagine if the Demo.js file is on a server in another domain? Will there be a problem with the results? I can also be very responsible to tell you: No! You can change the demo.js in the above example to: Http://demo.hpyer.cn/php/jsonp.php?callback=say try again.
Now, smart you should already understand what the JSONP is all about, then explain the first sentence at the beginning of this section. Looking at the contents of the Demo.js file, it should be known that it is just a call to a function (usually called a callback function), and that the data that needs to be interacted with is returned by the parameter situation. So the server accessed through JSONP needs to provide an interface that can set the name of the callback function, like the callback in Http://demo.hpyer.cn/php/jsonp.php?callback=say, so, in summary JSONP Server-side support is required. Attach the source code of jsonp.php:

<?php$type = isset ($_get[' type ')? $_get[' type ': '; $callback = isset ($_get[' callback '])? $_get[' callback ': '; $json = ', if ($type = = ' json ') {$json = ' {' Image ': {"Width": +, "Height": $, "tit Le ":" View from 15th Floor "," Thumbnail ": {" Url ":" http://www.example.com/image/481989943 "," Height ":," Width ":" "}," IDs ": [116, 943, 234, 38793]} ';} else {$json = ' "Hello, everyone!" ';} if (!empty ($callback)) {$json = $callback. ' ('. $json. ‘)‘;} Echo $json;

Applications in jquery:
Since the 1.2 release, JQuery has added support for JSONP. We can easily use the $.getjson () method (or other $.ajax ()-based methods) to load JSON data across domains. Here's an example:

<! DOCTYPE html>

You may have noticed in the example above that the URL was written as http://demo.hpyer.cn/php/jsonp.php?type=json&callback=, and it is important to note that this question mark will be Automatically replaced with the function name of the callback function (if it is an anonymous function, JQuery will automatically generate a time-stamped letter name).

Look at one of my examples in the project:

Define AJAX functions function Ajaxfun () {    var timeStamp = Math.floor (new Date (). GetTime ()/+);   & nbsp var url = "Http://apiso.alidemo.3gpp.cn/httpserver/cp/yisou/ali_feedback_interface.php?callback=jsonpCallback &feedbacktype=add&type= "+ feedbacknumber +" &book= "+ me.mixedInfo.title +" &author= "+ Me.mixedInfo.author + "&chapter=" + me.mixedInfo.cname + "&chapterid=" + me.mixedInfo.cid + "&questiondesc=" + text + "&platform=1&t=" + TimeStamp + "&sn=" + MD5 ("d30fcd1a9f1900fa049b4766e0a275e1" + timeStamp);  &n bsp;  var scriptobj = document.createelement ("script");    scriptobj.src = url;    Scriptobj.id = "Jsonpscript";    document.body.appendChild (scriptobj);   // JSONP callback function, Jsonpcallback must be a global function, because JSONP returns the statement that executes the function in the global environment, that is, Jsonpcallback (data)     Window.jsonpcallback = function (data) {        switch (data.code){            case "1":                 Novel.readerprompt (' Submit successful, coming back ... ', 1, function () {                      Window.history.go ( -1);                });                break ;            case "0":                 Novel.readerprompt (' Submit failed. ', 2);                break;             case ":      "           novel.readerprompt (' Commit failed, validation failed. ', 2);                break;        }       //delete scriptobj after success, The following settimeout will not execute the         if (document.getElementById ("Jsonpscript")) {             document.body.removeChild (scriptobj);        }   }   //Set time-out, time-out, direct display of submission success     SetTimeout (function () {        if (document.getElementById ("Jsonpscript")) {             document.body.removeChild (scriptobj);             Novel.readerprompt (' Submit successful, coming back ... ', 1, function () {                Window.history.go ( -1);           });        }   }, 2000);} Ajaxfun ();

Principles and applications of JavaScript cross-domain and JSONP

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.