Jsonp usage in javascript and cross-origin instances

Source: Internet
Author: User
Tags json php code script tag

Asynchronous JavaScript and XML (Ajax) is currently one of the key Web development technologies, allowing client JavaScript to interact with the server through HTTP.

The security model of the browser specifies that XMLHttpRequest and frames must be in the same domain name for communication. This is the so-called "same-origin policy restriction ".

For the sake of Web application security, the same-origin policy is not bad, but when we really need to request data under other domain names, this policy does cause trouble.

To overcome this restriction:

1. Request your own server to act as a proxy and forward the request to a real third-party server. This solution is widely used, but it seems a waste.

2. Flash. You must deploy a crossdomain. xml file on the server and develop the function in Flash for cross-domain purposes. However, it is costly to learn the AS development language.

3. Use the <script src = ""> label to insert the script. The script source in the tag points to a third-party server, because the same-source policy does not prevent the script of a third-party server from being imported into the tag. JSON can be used to improve the solution. The disadvantage is that it is difficult to debug and be used by untrusted services.


JSONP belongs to 3rd solutions.

JSONP (JSON with Padding) is an unofficial protocol. Its implementation method is simple, but it requires the cooperation of the server. Basically: let the client decide the Javascript function name to be called back, assemble JSON data into the callback function name on the third-party server, and return the function call script whose parameter is JSON data, the browser loads the script and executes it to obtain third-party data. The following is the initial implementation code.

Client code:

<Script type = "text/javascript">
Function jsonpCallback (result ){
Alert (result. );
Alert (result. B );
Alert (result. c );
For (var I in result ){
Alert (I + ":" + result [I]); // cyclically output a: 1, B: 2, etc.
}
}
</Script>
<Script type = "text/javascript" src = "http://crossdomain.com/services.php? Callback = jsonpCallback "> </script>

Server services. php code:

<? Php
// JSON data returned by the server
$ Data = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
$ Result = json_encode ($ data );

$ Callback = $ _ GET ['callback'];
Echo $ callback. "(". $ result. ")"; // dynamically executes the callback function.


$. GetJSON $. ajax $. get in jQuery is also useful to JSONP. I don't know if you have noticed it.

Same-origin policy

First, for security reasons, the browser has a same-source policy. The same-source policy prevents you from retrieving or setting attributes of documents loaded from one source. It seems that you don't know what it means.

1. Create two webpages at will

Add the following configuration in your apache httpd. conf configuration file:

Apache

Listen 11111.
Listen 22222.
 
Namevirtualhost local host: 11111
Namevirtualhost local host: 22222
 
<VirtualHost localhost: 11111>
ServerAdmin tangrucheng@gmail.com
ServerName localhost: 11111
DocumentRoot E:/wamp/www/test/test11111
</VirtualHost>
 
<Directory "E:/wamp/www/test/test11111">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow, deny
Allow from all
</Directory>
 
<VirtualHost localhost: 22222>
ServerAdmin tangrucheng@gmail.com
ServerName localhost: 22222
DocumentRoot E:/wamp/www/test/test22222
</VirtualHost>
 
<Directory "E:/wamp/www/test/test22222">
Options Indexes FollowSymLinks
AllowOverride None
Order allow, deny
Allow from all
</Directory>
Such a port is 11111, and a port is 22222, which is different from the source according to the definition.


 2. Use jQuery to initiate requests with different sources

Add a button on the webpage with Port 11111, and Click the event to initiate a request to the port 22222 domain:

 

<Html>
<Head>
<Title> 11111 </title>
</Head>
<Body>
<Button id = "get22222"> Click </button>
 
<Script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ ("# Get22222"). click (function (){
$. Get ("http: // localhost: 22222/js/jquery. min. js", function (data ){
Console. log (data)
})
 
$. Get ("http: // localhost: 22222/index. php", function (data ){
Console. log (data)
})
})
</Script>
</Body>
</Html>

According to the same-origin policy, it is obviously tragic. The browser will stop and will not initiate this request.


OK. In the past, jsonp had to solve this problem.
 

Cross-Origin capability of script tags

I don't know if you know about CDN. For example, if you use Microsoft CDN, jQuery is not available on our webpage, which is provided by Microsoft's website:

XHTML

<Script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type = "text/javascript"> </script>

Go back to the webpage with Port 11111. We have a request for the jQuery file of port 22222 in the Click event. This request uses the script tag.

XHTML

<Script type = "text/javascript" src = "http: // localhost: 22222/js/jquery. min. js"> </script>
Of course, 200, OK.

 


In the same way, a webpage on port 11111 initiates a request to the 22222 domain and sets the scr attribute in the script. The other method is tragic. Using the cross-origin capability of scripts is the basis of jsonp.

 Use scripts to obtain json from different sources

Since it is called jsonp, it is obviously in json format and cross-origin retrieval. According to the above analysis, it is easy to think: use js to construct a script tag, assign the json url to the scr attribute of the script, insert the script into the dom, and let the browser get it. Practice

E: \ wamp \ www \ test \ test11111 \ index. phpPHP
<Html>
<Head>
<Title> 11111 </title>
</Head>
<Body>
<Button id = "get22222"> Click </button>
 
<Script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Function CreateScript (src ){
$ ("<Script> </script>"). attr ("src", src). appendTo ("body ")
        }
$ ("# Get22222"). click (function (){
CreateScript ("http: // localhost: 22222/index. php ");
})
</Script>
</Body>
</Html>


E: \ wamp \ www \ test \ test22222 \ index. phpPHP

 
<? Php
 
$ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
 
Echo json_encode ($ arr );

 

First, the first browser, http: // localhost: 22222/index. the php Url is indeed in json format, and the script label is used on the port 11111 webpage to request the Url 22222 is also OK, but the js syntax error is reported at the bottom. After loading the script tag, the response will be executed as js immediately. Obviously {"a": 1, "B": 2, "c": 3, "d": 4, "e": 5} is not a legal js statement.
 
Use scripts to obtain exotic jsonp

Obviously, putting the above json in a callback method is the simplest method. For example:

E: \ wamp \ www \ test \ test22222 \ index. phpPHP

<? Php
 
$ Callback = $ _ GET ['callback'];
 
$ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
 
Echo $ callback. '('. json_encode ($ arr ).')';

If the jsonpcallback method exists, then jsonpcallback ({"a": 1, "B": 2, "c": 3, "d": 4, "e ": 5}) is a valid js statement.

Because the server does not know what the client callback is, it is impossible to hard code it into jsonpcallback, so it takes a QueryString to let the client tell the server what the callback method is. Of course, the key of QueryString must comply with the conventions of the server. The above is "callback".

Add callback function:

JavaScript

Function jsonpcallback (json ){
Console. log (json)
}

Change the parameters of the preceding method slightly:

JavaScript

$ ("# Get22222"). click (function (){
CreateScript ("http: // localhost: 22222/index. php? Callback = jsonpcallback ");
})

200OK, the server returns jsonpcallback ({"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }), we have also written the jsonpcallback method, which of course will be executed. OK successfully obtained json. That's right. Here it's all about jsonp.
 

Get jsonp using jQuery

In the above method, we have to insert the script tag and define a callback, which is a little troublesome. Using jQuery, we can directly obtain the desired json data, which is also the jsonp above (the server code remains unchanged ):

E: \ wamp \ www \ test \ test11111 \ index. phpXHTML

<Html>
<Head>
<Title> 11111 </title>
</Head>
<Body>
<Button id = "get22222"> Click </button>
 
<Script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ ("# Get22222"). click (function (){
$. Ajax ({
Url: 'http: // localhost: 22222/index. Php ',
DataType: "jsonp ",
Jsonp: "callback ",
Success: function (data ){
Console. log (data)
                }
})
})
</Script>
</Body>
</Html>

The result is the same as above.
 

Summary

In a word, the script tag is used to bypass the same-origin policy to obtain such data. jsonpcallback is a callback method for the page, and the parameter is the desired json.

JavaScript

Jsonpcallback ({"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 })

The same-origin policy is established for security reasons. Initiating requests with different origins is considered insecure and unacceptable, but why is it acceptable to go around a small circle like this? Is this safe? It feels like people are afraid of being seen while taking a bath, closing the door, but the big window on the side is open. Does this make sense? What do you think of Yuanfang?

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.