Quest Ajax Cross-domain Request _ajax related

Source: Internet
Author: User
Tags json domain server

Objective

Ajax, with the pale words of praise: very good.

We can use AJAX to achieve asynchronous data acquisition, reduce server operation time, greatly improve the user experience; we can use Ajax to implement small system combination large system, we can also use AJAX to achieve front-end optimization. (A ranking)

While Ajax is good, there is a limit to how it can be used, and cross-domain communication is not allowed for security reasons. If you try to request data from a different domain, a security error occurs. (The following example 1 can be seen visually)

Homology Policy restrictions

The homology policy prevents scripts loaded from one domain from acquiring or manipulating document properties on another domain. In other words, the domain of the requested URL must be the same as the current Web page's domain. This means that the browser isolates content from different sources to prevent action between them. This browser strategy is very old and has been around since Netscape Navigator version 2.0. --Excerpted from Developerworks
The so-called homology is refers to, domain name, protocol, port same.

A roar on the ground

This article explains how to use Ajax to implement Cross-domain request, then know "homology strategy", can solve many questions: "For Mao my Ajax load data!" "For the Fur browser console will give me such a beautiful code error!" ”

Example 1
First, a bug demonstration.

Client code:

Copy Code code as follows:

<script>
The client uses the Getjson method to request a script on another machine
$.getjson ("http://172.22.22.120/new/ajax.php", function (JSON) {
alert (json.website);
});
</script>

Server-side PHP scripting code:

Copy Code code as follows:

<?php
ajax.php
Header (' Content-type:application/json ');

echo json_encode (Array (' website ' => ' hcoding '));
?>

Firefox under the error hint:

According to the concept of homology policy, localhost and 172.22.22.120 are under different domain names, so cross-domain requests are rightfully rejected by browsers.

JSONP

JSONP (JSON with Padding) is a "usage pattern" of data format JSON that allows pages to be data from other domains. Another new way to solve this problem is to share across source resources. Because of the homology policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, while HTML <script> elements are an exception. Using this open policy of <script> elements, Web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP. The data captured by JSONP is not JSON, but arbitrary JavaScript, executed using a JavaScript literal instead of parsing with the JSON parser. --Excerpt from Wikipedia
How do you understand that? I personally think so, using <script> cross-domain request data, the Cross-domain server returns a "JavaScript code", yes, you're right, not JSON format data, JavaScript code, so that this code is made up of JavaScript The literal interpreter executes. The example above is more intuitive:

Example 2
Client code:

Copy Code code as follows:

<script>
This is the callback method.
function CB (data) {
alert (data.website);
}
</script>
<!--This is a Cross-domain request code, remember that this code is to be--> after the callback function
<script src= "HTTP://172.22.22.120/NEW/AJAX_JSONP.PHP?CALLBACK=CB" ></script>

Server-side PHP scripting code:

Copy Code code as follows:

<?php
$CB = Htmlspecialchars ($_get[' callback ')); Note that this is a good filter to prevent XSS attacks.
Echo $CB, ' (', Json_encode (' website ' => ' hcoding '), ') '; The data returned by the client is: CB ({"Name": "Hcoding"}) This is a JS code
?>

What will happen to the browser, I will not say, of course, the CB method is called:

So, again, with the concept of JSONP, using <script> not subject to the same-origin policy, Cross-domain servers return the JSON data to the client as parameters and callback functions.

jquery's support for JSONP

This article is going to talk about the Cross-domain request of Ajax, so many of the above, of course, the following topic.

Starting with version 1.2, JQuery has local support for JSONP callbacks. If you specify a JSONP callback, you can load the JSON data that is located in another domain, and the callback syntax is: url?callback=? JQuery automatically will? Replace with the name of the build function to invoke.

Example 3:$.getjson method Cross domain request
Example 4:$.ajax method Custom callback method
Example 3
Client code:

Copy Code code as follows:

<script>
The client uses the Getjson method to request a script on another machine
The browser generates a random callback parameter
$.getjson ("http://172.22.22.120/new/ajax_jsonp.php?callback=?", function (JSON) {
alert (json.website);
});
</script>

Server-side PHP scripting code:

Copy Code code as follows:

<?php
$CB = Htmlspecialchars ($_get[' callback ')); Note that this is a good filter to prevent XSS attacks.
Echo $CB, ' (', Json_encode (' website ' => ' hcoding '), ') '; Returns the client's data, this is a section of JS code
?>

$.getjson is easy to use, but you cannot specify a callback function.

Example 4
Client code:

Copy Code code as follows:

<script>
$.ajax ({
Type: "Get",
URL: "http://172.22.22.120/new/ajax_jsonp.php",
DataType: "Jsonp",//data format specified as Jsonp
JSONP: "Callback",//Service Point gets callback method via this key value
Jsonpcallback: "CB",//Specify callback method
Success:function (JSON) {
},
});
callback method
function CB (data) {
alert (data.website);
}
</script>

The server-side PHP scripting code is the same as example 3.

Summarize

It is a good moral character to follow the homologous strategy according to the so-called radius, taking security as the starting point. But we also have requirements for Cross-domain requests, and JSONP can meet our needs. There are, of course, many ways to cross domain requests, not just JSONP.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.