Native JS implementation of Ajax cross-domain requests

Source: Internet
Author: User
Tags script tag

How does native JS implement cross-domain requests for Ajax?

Before we solve this problem, we must first understand why we want cross-domain requests, and under what circumstances cross-domain requests.

Understand: "Homologous strategy", you know;

The same-origin policy restricts how a document or script loaded from one source interacts with a resource from another source. This is a key security mechanism for isolating potentially malicious files.

It is defined as:

A script requests data back to the table, only the data belonging to the same protocol name, the same host name, and the same port number are read;

Therefore, when requesting different protocol names, different port numbers, and files under different host names,

Will violate the same-origin policy, unable to request success, need to cross-processing!!

Ways to resolve cross-domain requests:

Method One:

Setup via PHP in the background

The front desk does not need any settings and writes a header to the PHP file that was requested in the background.

Header ("access-control-allow-origin:*"); ---Indicates which domain names are allowed to request this PHP file, * indicates that all domain names are allowed

JS Code:

$.post ("http://127.0.0.1/json.php",function(data) {   console.log (data);});

Comments:

Where the URL is the path to the PHP file;

PHP Code:

<?PHPHeader("Content-tyepe:text/html;charset=utf-8"); Header("access-control-allow-origin:*"); $str= <<<Str [{"Name": "Shadow", "age": +, "hobby":    [                    "Eat", "drink", "play", "le"            ], "Score":{                    "Math": +, "Chinese": 89            }        },]str;Echo $str;

Results:

  

Method Two:

Implementation steps: 

    1, the original SRC attribute label sub-band cross-domain function; You can use the SRC attribute of the script tag to request background data

<script src= "http://127.0.0.1/json.php" ></script>

2, for SRC after loading the data successfully, will be loaded directly into the script tag;

Therefore, returning the JSON string directly from the background cannot be resolved in the script tag.

Therefore, the background should return a callback function name to the foreground and pass the JSON string as a parameter.

Back in the background php file: Echo "callback ({$json})";

3. The foreground receives the callback function that is returned and will be called directly in the script tag. Therefore, it is necessary to declare such a callback function as a callback for the successful request

function Callback (data) {     alert ("Request succeeded!!!") );     Console.log (data); }

JS Code:

<script type= "Text/javascript" >        function  callback (data) {               console.log (data);         } </script><script src= "http://127.0.0.1/json.php" ></script>

PHP Files:

<? PHP     Header ("Content-tyepe:text/html;charset=utf-8");     $str = <<<str    [    {        "name": "Yingzi",        "age": +,        "hobby":[             "Eat",            "Drink",            "play",            "le"        ,    }]str; Echo "Callback ({$str})";

Results:

Method Three:

   1, in the AJAX request, set datatype to "JSONP";

2, back in the background, still need to return the callback function name, however, Ajax when sending a request, the default is to use a GET request to send the callback function name to the background,

Background $_get[' callback '] Remove function name:

---echo "{$_get[' callback '} ({$str})";

3, back in the background, the foreground can use the Ajax success function as a successful callback

---success:function (data) {}

JS Code:

<script type= "Text/javascript" >    $.ajax ({        type:"POST",        URL:"http://127.0.0.1 /json.php ",        dataType:" Jsonp ",        success:function(data) {            Console.log (data);        }    ); </script>

PHP Files:

<? PHP     Header ("Content-tyepe:text/html;charset=utf-8");     $str = <<<str    [    {        "name": "Yingzi",        "age": +,        "hobby":[             "Eat",            "Drink",            "play",            "le"        ,    }]str; Echo "{$_get[' Callback ']} ({$str})";

Results:

Of course, the background can also casually return a function name, the foreground as long as the request succeeds, it will automatically call this function. Similar to the second ②, ③ step, without the need for this method of step ③

PHP return: Echo "callback ({$STR})";

JS Code: Function callback (data) {

Console.log (data);

}

JS Code:

<script type= "Text/javascript" >    $.ajax ({        type:"POST",        URL:"http://127.0.0.1 /json.php ",        dataType:" Jsonp ",    });     function (data) {        console.log (data);    } </script>

PHP Files:

<? PHP     Header ("Content-tyepe:text/html;charset=utf-8");     $str = <<<str    [    {        "name": "Yingzi",        "age": +,        "hobby":[             "Eat",            "Drink",            "play",            "le"        ,    }]str; Echo "Callback ({$str})";

Results:

Web front-end engineer, about the data interaction this piece, will use a lot of places; this is the great God "shadow" of the article, I was shameless to carry over, if the "shadow" see the request to delete please contact me; The following is a "shadow" blog original link: https://www.cnblogs.com/ 2502778498spw/p/7784390.html

Native JS implementation of Ajax cross-domain requests

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.