Ajax requests are always unsuccessful? Browser-origin policy and cross-domain issues

Source: Internet
Author: User
Tags ming

Scene

The code farmer Xiao Ming wants to make a big screen showing the business data to the boss, which contains the data from his own website and the old king from the next door.
Then the data on your own site provides a data interface such as Http://xiaoming.com/whoami.
The old king next door provided a data interface such as Http://oldwang.com/isdad.
It's no problem to open them alone. However, an AJAX request that uses JS cannot receive data from oldwang.com.
Click on the browser console to see the Red Letter marked (Chrome):

load http://oldwang.com/isdad. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://xiaoming.com/‘ is therefore not allowed access.

This is where cross-domain issues are encountered.

Why is there such a problem?

Imagine if the next-door Lao Wang does not know you, his website has a variety of user interface, order interface, the article interface, then who can put the data returned by these interfaces directly on their own website, or real-time.

So the browser has developed a homologous policy that restricts the acquisition of resources from another source (origin) from a script in one source (origin).

What is homologous

If two pages have the same protocol (PROTOCOL:HTTP), Port (port:80), and Host (host:xiaoming.com), then the two pages belong to the same source (origin).

Solution Solutions

This does not talk about the IFRAME, Flash, etc. many years ago, only a few of the most commonly used scenarios

Cross-domain between a.x.com and b.x.com

Sub-domains are also subject to cross-domain restrictions. This is the simplest problem, simply declaring the page as a more advanced domain.

<script>  document.domain = "x.com";</script>
The most classic, efficient, browser-compatible solution: JSONP

See the name of Jsonp a lot of people think this is a cross-domain black technology that is closely related to JSON, but actually from a cross-domain perspective, with JSON does not have a dime relationship, he is using the browser allows cross-domain loading JS and other resources to obtain data.

Because the browser supports cross-domain loading JS <script src="http://aliyun.com/....."></script> , so it is very simple, you can wrap the data into JS on it.

This is the data that is loaded into the data by script that cannot be "executed" and is not passed to the Ajax callback function:

{  "data": 123}

This is the JS script, as long as the callback Ajax callback function is associated with, you can tell the data to the callback function:

callback({  "data": 123})

This can be seen in two points:

First, need callback and Ajax callback function binding;
Second, the data server needs to cooperate.
Third, only get requests are supported

Front End If you have completed the encapsulation of the entire value process with jquery,jquery, the logic is:
1. Randomly generate a non-repeating callback function name and bind to the Ajax callback function.
1. Place the callback function name into the query string for the URL, ashttp://oldwang.com/api?callback= jQuery214015557975923291245_1460532274390
1. Generate a <script> label to use the above URL as SRC
1. Wait for the data to load and pass the data to the AJAX callback function

Back end in PHP, for example, the logic is to get the browser came up with a parameter as callback wrapper data:

<?php  echo $_GET[‘callback‘]."(". $data .")";?>
Most new browsers are compatible with CORS (cross Origin Resource sharing)

His principle is the next door to the old Wang initiative to tell the browser "Do not stop Xiao Ming, we are relatives ..."
So the simplest example is to include in the header information returned by the data server:

Access-Control-Allow-Origin: http://xiaming.com

However, this header information does not support enumeration, if the next door of the old king's relatives too much can only be generated by the program to dynamically generate this header information, in PHP, for example:

<?php if (is_my_bastard($_SERVER[‘HTTP_ORIGIN‘])) { header("Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN‘]}");}?>

If Lao Wang was a good man, he would not be. Then you can use it directly *

Access-Control-Allow-Origin: *
Cookies

Cors is the default without cookie information, if you want to bring a cookie to add the Withcredentials parameter, in jquery as an example:

$.ajax({    url: "http://laowang.com/isdad",    xhrFields: {      withCredentials: true } });

The server also needs to add the header information to allow Credentials and not allow the wildcard "*", as in the following code

<?php if (is_my_bastard($_SERVER[‘HTTP_ORIGIN‘])) { header("Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN‘]}"); // 不允许用 * Access-Control-Allow-Credentials:true}?>

Ajax requests are always unsuccessful? The browser's Origin policy and cross-domain issues are detailed

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.