Cross-domain Problem JSONP

Source: Internet
Author: User

Have to say the same Origin policy:

Homologous strategy, which is a well-known security policy proposed by Netscape. This policy is now used by all JavaScript-enabled browsers. The so-called homologous refers to the domain name, protocol, Port the same. When a browser's two tab pages are opened to Baidu and Google's page when a Baidu browser executes a script will check which page this script belongs to, that is, check whether the same origin, only and Baidu homologous script will be executed.

That's why you can't get data, so how do you solve cross-domain problems? Yes, we can get to the point now to understand what is JSONP .

1<!DOCTYPE HTML5>
2<Html>
3<Head>
4<Title>test</Title>
5<Scripttype= "Text/javascript" Src= "test.js" ></ Script>,
6 </< Span style= "COLOR: #800000" >head>
7 <body>
8 </body>
9 </ html>
Test.js:
1 alert ("Success");

let's go back up and look at Jsonp. The description of the definition describes the form of JavaScript callback. So let's change the code, how to implement the Jsonp JavaScript callback form. part of the Code for sample in program a:

1<ScriptType= "Text/javascript">
2//callback function
3 function callback (data) {
4 alert ( Data.message);
5 }
6 </script>
7 <script Type= "Text/javascript" src = "http://localhost:20002/test.js" ></script>

Code for Test.js in program B:

call the callback function and use the JSON data as an elaboration pass, complete the callback
2 Callback ({message: "Success"});

This is actually the simple implementation pattern of JSONP, or the JSONP prototype: Create a callback function and then call the function on the remote service and pass the JSON data as parameters to complete the callback .

populates the JSON data into the callback function .

In general, we want this script tag to be dynamically invoked, rather than as it is fixed in HTML, so it does not wait for the page to display. We can create script tags dynamically through JavaScript, so we can invoke remote services with flexibility.

Part of the Code for sample in program a:

1<ScriptType= "Text/javascript">
2functionCallback (data) {
3alert (data.message);
4}
5//Ways to add <script> tags
6functionAddscripttag (SRC) {
7VarScript=Document.createelement (‘Script‘);
8Script.setattribute ("Type","Text/javascript");
9Script.src=Src
10Document.body.appendChild (script);
One }
A
window.onload = function() {
Addscripttag ("http://localhost:20002/test.js");
}
</script>
Program B's test.js code does not change, we execute the next program, is not the same as the original. If we want to invoke a remote service again, just add the Addscripttag method, and the SRC value of the remote service is allowed. Here is why the Addscripttag method into the Window.onload method, because the Addscripttag method has a sentence document.body.appendChild (script); This script tag is added to the body, because we write the JavaScript code in the head tag, Document.body has not been initialized, so we have to initialize the page through the Window.onload method , This will not make mistakes.

The above example is the simplest JSONP implementation model, but it is not really a JSONP service. Let's look at what the real Jsonp service is like, such as Google's Ajax search interface:http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?& Callback=?

Q=? This question mark indicates what you want to search for, and most importantly, the second callback=? This is the name of the callback function, which is named after its name, that is, the function name of your client-defined callback function is passed to the server, and the server returns a method with the name of the callback function you have defined. The retrieved JSON data is passed into this method to complete the callback. A bit wordy, or look at the implementation of the Code it:

1<ScriptType= "Text/javascript">
2//Ways to add <script> tags
3functionAddscripttag (SRC) {
4VarScript=Document.createelement (‘Script‘);
5Script.setattribute ("Type","Text/javascript");
6Script.src=Src
7Document.body.appendChild (script);
8}
9
10Window.onload=function(){
11//Search Apple to pass the custom callback function name result into the callback parameter
12Addscripttag ("Http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=apple&callback=result");
13
14 "
15 // custom callback function Result
16 function result (data) {
17 // we simply get the URL data in the first record of Apple search results
Span style= "COLOR: #008080" >18 alert (Data.responsedata.results[0].unescapedurl);
19 }
20 </script>

This completes a most basic JSONP service call, is not very simple, below we to understand how jquery is called Jsonp.

The realization of jquery to Jsonp

The jquery framework also certainly supports JSONP, which can be used with the $.getjson (Url,[data],[callback]) method (see http://api.jquery.com/jQuery.getJSON/for details). Then we will modify the code of the program A, instead of the jquery Getjson method (The following example is useless to the service, so only write Getjson (Url,[callback])):

<ScriptType= "Text/javascript"Src= "Http://code.jquery.com/jquery-latest.js"></Script>, 
<script type= "Text/javascript" >< Span style= "COLOR: #000000" >
$.getjson ( "http:// Localhost:20002/myservice.ashx?callback=? ",function Alert (data.name + " is a a "+ Data.sex);
});
</script>

The result is the same, note that after the URL must be added a callback parameter, so that the Getjson method will know is to use JSONP way to access the service, callback the question mark is the internal automatically generated a callback function name. This function name you can debug a bit to see, such as jquery17207481773362960666_1332575486681.

Of course, adding that we want to specify our own callback function name, or how to fix a fixed callback function name on the service? We can use the $.ajax method to implement (more parameters, detailed reference to Http://api.jquery.com/jQuery.ajax). Let's take a look at how to achieve it:

<ScriptType= "Text/javascript"Src= "Http://code.jquery.com/jquery-latest.js"></Script>
<ScriptType= "Text/javascript">
$.ajax ({
Url:"http://localhost:20002/myservice.ashx?callback=? " Datatype:jsonp " Jsonpcallback: "person" Success:function ( Data) {
Alert (data.name + " is a a "+ Data.sex);
}
});
</script>

Yes, Jsonpcallback can specify our own callback method name person, and the remote service accepts that the value of the callback parameter is no longer an auto-generated callback name but a person. DataType is to specify that the remote service is accessed in jsopn manner.



Cross-domain Problem JSONP

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.