Ajax cross-domain request learning notes

Source: Internet
Author: User
Tags domain server

Objective

Ajax, with pale words of praise: very well.

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

Although Ajax is good, there are certain limitations in use, 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)

Same-Origin policy restrictions

The same-origin policy prevents scripts loaded from one domain from getting or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is very old and exists from Netscape Navigator version 2.0. --Excerpt from Developerworks

The so-called homology refers to the same domain name, protocol, and port.

A roar on the ground

This article explains how to use Ajax to achieve cross-domain requests, then know the "same-Origin strategy", you can solve a lot of questions: "For Mao my ajax can't load data!" "" For the Hair browser console will give me such a beautiful code error! ”

Example 1

First, one error demonstration.

Client code:

<script>    //  clients use 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 script code:

<? PHP     // ajax.php    Header (' Content-type:application/json ');    echo Json_encode (Array (' website ' = ' hcoding '));? >

Error message under Firefox:

According to the concept of the same-origin strategy, localhost and 172.22.22.120 are under different domain names, so cross-domain requests are naturally rejected by the browser.

JSONP

JSONP (JSON with Padding) is a "usage pattern" of data format JSON that allows Web pages to have data from other domains. Another new way to solve this problem is to share resources across sources. Because of the same-origin 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 strategy of <script>, the Web page can get JSON data that is dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser. --Excerpt from Wikipedia

How do you understand that? I personally think that, with <script> cross-domain request data, cross-domain servers return a piece of "JavaScript code", yes, you are right, not JSON format data, is JavaScript code, so that this code by JavaScript The literal interpreter executes. The example above is more intuitive:

Example 2

Client code:

<script>    //  This is the callback method    function  CB (data) {        alert (data.website);    } </script><!--This is the code for cross-domain requests, remember that this code--><script src= "http://172.22.22.120/new/ajax_jsonp.php after the callback function? CALLBACK=CB "></script>

Server-side PHP script code:

<? PHP     $CB Htmlspecialchars ($_get[' callback ']);  // Note that filtering is a good place to prevent XSS attacks    Echo $CB, ' (', Json_encode (' website ' = ' hcoding '), ') ';  // the data returned to 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 the concept of JSONP, using <script> is not limited by the same-origin policy, the cross-domain server returns the JSON data as parameters and callback functions along with the client.

jquery's support for JSONP

This article to talk about the cross-domain Ajax request, the front said so much, the following of course to talk about the subject.

Starting with version 1.2, JQuery has local support for the JSONP callback. If you specify a JSONP callback, you can load the JSON data that is located in the other domain, with the syntax of the callback: 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:

<script>    //  clients using the Getjson method to request a script    // browser on another machine 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 script code:

<? PHP     $CB Htmlspecialchars ($_get[' callback ']);  // Note that filtering is a good place to prevent XSS attacks    Echo $CB, ' (', Json_encode (' website ' = ' hcoding '), ') ';  // returns the client's data, which is a section of JS code ?>

$.getjson is simple to use, but it is not possible to specify a callback function.

Example 4

Client code:

<script>    $.ajax ({        "GET",        "http://172.22.22.120/new/ajax_jsonp.php",         "Jsonp",    //  data format specified as Jsonp        JSONP: "Callback",     //  The service point gets the callback method through this key value        jsonpcallback: "CB",   //  Specify callback method        function (JSON) {        },    });       // callback Method    function CB (data) {        alert (data.website);    } </script>

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

Summarize

The so-called inadequate surrounding area, to security as the starting point, follow the same-origin strategy is a good character. But we also have requirements for cross-domain requests, and JSONP can meet our needs. Of course there are many ways to cross-domain requests, not just JSONP.

This article link: http://www.hcoding.com/?p=238

Original articles, reproduced please specify: jc&hcoding.com

Ajax cross-domain request learning notes

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.