Several common Ajax cross-domain requests

Source: Internet
Author: User
Tags script tag

Objective

first, we need to understand what is cross-domain and why cross-domain. There is a homologous policy in JS. When requesting a file with different protocol names under different port numbers, it will violate the same origin policy and cannot be requested successfully! Cross-domain processing is required!

This article will give you a detailed introduction of the three kinds of cross-domain methods used by individuals, to request PHP as an example.

1header ("access-control-allow-origin:*");

Background PHP settings, the foreground does not need any settings, in the background of the requested PHP file, write a header. Indicates which domain names are allowed to request this PHP file, * indicates that all domain names are allowed

eg

Front desk:

$.post ("http://localhost/lianxi/kuayu.php", function (data) {                console.log (data);            })

Background:

header ("access-control-allow-origin:*"); $str = < <<str [    {        "name": "Zhangsan",        "age": +, "        hobby": [            "Eat",            "Drink",            "play",            "le"        ],        "Score": {            "math": "            Chinese":    }]str;echo $str;

Front desk return:

2 using the SRC attribute +jsonp to implement cross-domain

① the label used for the SRC attribute has a cross-domain function, so you can request background data using the SRC attribute of the script tag.

② since SRC successfully loads the data, the loaded content is placed directly into the script tag. So the back-end directly returns a JSON string that cannot be parsed in the script tag. Therefore, the background should return a callback function to the foreground and pass the JSON string as a parameter.

③ The front desk receives the callback function that is returned, which is called directly in the script tag. It is therefore necessary to declare such a callback function as a callback for the successful request.

Jsonp:json with padding is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers.

Front desk:

<type= "Text/javascript">        function  callBack (data ) {            console.log (data);            }     </ Script >    <  type= "Text/javascript"  src= "http://localhost/lianxi/kuayu.php"  ></script>

Background:

header ("Content-type:text/html;charset=utf-8"); $str = < <<str [    {        "name": "Zhangsan",        "age": +, "        hobby": [            "Eat",            "Drink",            "play",            "le"        ],        "Score": {            "math": +,            "Chinese": +        }    ,    ]str;echo "CallBack ({$str})";

Front desk return:

3Ajax implementations of jquery Jsonp

① set datatype to "Jsonp" when Ajax is requested


The callback function name still needs to be returned when the ② backend returns. But Ajax, when sending a request, uses the GET request callback function name to be sent back to the background by default, and can use $_get[' callback '] to take out the name of the callback
Echo ' {$_get[' callback '} ({$str}) ";


③ back in the background, Ajax can still use success as a successful callback function:
Success:function (data) {}

Of course, the backstage can also be casually returned to the function name, echo "CallBack ({$json})"; The function is automatically called by the foreground whenever the request succeeds. ②③ steps like the second one

Front desk:

$.ajax ({                type: "Post",                URL: "http://localhost/lianxi/kuayu.php",                dataType: "Jsonp",                success: function (data) {                    console.log (data);                }            });

Background:

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

Front desk return:

only Yun-hee
The above is my common cross-domain approach, I hope to help you readers. Welcome criticism, communication and communication.

Several common 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.