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.html and HTTP are opened in the browser's two tab pages, respectively://www.google.com/ Index.html, which, JavaScript1 and JAVASCRIPT3 belong to Baidu's script, and JavaScript2 is a Google script, when the browser's tab1 to run a script, will be a homologous check, Only with 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 to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP 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).

<Scripttype= "Text/javascript">    functionJsonpcallback (Result) {alert (result.msg); }</Script><Scripttype= "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><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Demo</title></Head><Body><Scripttype= "Text/javascript">functionsay (words) {alert (words);}</Script><Scripttype= "Text/javascript"src= "Demo.js"></Script></Body></HTML>

Demo.js:

Say ("Hello, everyone!");

After running the demo.html file, it is not seen that reads "Hello, everyone!" 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, you should be wise enough to understand what's going on with JSONP, so let's 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": +, "Title": "View from 15th Floor", "Thumbnail": {"Url": "http://w ww.example.com/image/481989943 "," Height ":" Max "," Width ":" + "}," IDs ": [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><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Demo</title><Scripttype= "Text/javascript"src= "Jquery.js"></Script><Scripttype= "Text/javascript">functionDo_jsonp () {$.getjson ("http://demo.hpyer.cn/php/jsonp.php?type=json&callback=?",   function(data) {$ ('#result'). Val ('data. Image.ids:' +data.   Image.ids); });}</Script></Head><Body><ahref= "Javascript:do_jsonp ();">Click Me</a><BR/><textareaID= "Result"cols= " the"rows= "5"></textarea></Body></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:

//Defining AJAX FunctionsfunctionAjaxfun () {varTimeStamp = Math.floor (NewDate (). GetTime ()/1000); varurl = "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 + "&platfor m=1&t= "+ TimeStamp +" &sn= "+ MD5 (" d30fcd1a9f1900fa049b4766e0a275e1 "+TimeStamp); varScriptobj = 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 (' submitted successfully, coming back ... ', 1,function() {Window.history.go (-1);                });  Break;  Case"0": Novel.readerprompt (' Commit failed. ', 2);  Break;  Case"900": Novel.readerprompt (' Commit failed, validation failed. ', 2);  Break; }        //after successful deletion of Scriptobj, the latter settimeout will not be executed.        if(document.getElementById ("Jsonpscript") {document.body.removeChild (scriptobj); }    }    //set time-out, time-out, direct display of successful commitSetTimeout (function() {        if(document.getElementById ("Jsonpscript") {document.body.removeChild (scriptobj); Novel.readerprompt (' submitted successfully, coming back ... ', 1,function() {Window.history.go (-1);        }); }    }, 2000);} Ajaxfun ();

Original address: http://www.css119.com/archives/1789

On the principle and application 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.