Details about ajax cross-origin solutions and ajax cross-Origin

Source: Internet
Author: User

Details about ajax cross-origin solutions and ajax cross-Origin

Let's record some issues about ajax cross-origin today. For emergency purposes.

Cross-Origin

Same-origin policy restrictions

The same-origin policy prevents scripts loaded from one domain from obtaining or operating on document properties in another domain. That is to say, the domain of the requested URL must be the same as that of the current Web page. This means that the browser isolates content from different sources to prevent operations between them.

Solution

Generally, there are two common methods: one is to start from the server side and the other is to start from the client side. The two have their own advantages and disadvantages. Specific analysis is required for the specific method.

  1. Server Response Header
  2. Server proxy
  3. The client uses the script callback mechanism.

Method 1

The Access-Control-Allow-Origin keyword is set only on the server.
Will take effect. That is to say, even if the client uses

xmlhttprequest.setHeaderREquest('xx','xx');

It will not have any effect.

Normal ajax request

Next we will simulate the case implementation of ajax non-Cross-origin requests.

Test1.html

<! DOCTYPE html> 

The content of test1.PHP in the same directory is as follows:

<?phpecho "It Works.";?>

Cross-origin request

The HTML file and PHP file are both in the Apache container, so there is no cross-origin problem. Now, put the HTML file on the desktop and request PHP Data again, this creates a "cross-origin request.

Check the address bar of the browser.

The following error message is displayed when you access the service again.

To address this problem, you can set Access-Control-Allow-Origin.

Format: Access-Control-Allow-Origin: domain.com/xx/yy .*

If you know the domain name of the client or the fixed path of the request, it is best not to use wildcards to further ensure security. If you are not sure, use the * wildcard.

When the backend development language is PHP, you can start setting the file as follows:

header("Access-Control-Allow-Origin: *");

If it is An ASPX page, you need to set it like this (Java is similar ):

Response.AddHeader("Access-Control-Allow-Origin", "*");

Then, visit the path again.

Server proxy Mode

This method is a common and widely adopted method. The proxy is a bit too intrusive, but it is actually a message. Here is a small example:

James liked a girl named Xiaohong in Class 3, but he was embarrassed to ask for QQ numbers. Then let's talk to Xiaolan, a girl from her own class. Help yourself. So Alan is equivalent to a proxy. Help James obtain the contact information that he could not directly obtain.

The following is an example to illustrate this problem.

Direct Cross-origin requests

Modify the URL to allow ajax to directly request data from other websites.

<! DOCTYPE html> 

The result is as follows:

Enable proxy Mode

For the HTML page, we still use our own interface:

url = 'http://localhost/learn/ajax/test1.php';

The details are as follows:

<! DOCTYPE html> 

Then the corresponding test1.php should help us implement the data request process, get the "Red contact information" and return it to "James ".

<?php$url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=hello%20world.';$result = file_get_contents($url);echo $result;?>

The following describes the code execution result.

Jsonp Method

JSONP (JSON with Padding) is inspired by loading the script TAG content on the HTML page. The browser always loads the content corresponding to the src attribute of the script. So:

An ideal way to overcome this restriction is to insert a dynamic script element into the Web page. The page source points to the service URL in another domain and obtains data in its own script. When the script is loaded, it starts to execute. This method is feasible because the same-origin policy does not prevent dynamic script insertion and regards the script as being loaded from the domain that provides the Web page. However, if the script tries to load the document from another domain, it will not succeed.

The implementation idea is:

Assemble the preset json data of the client on the server side and send it back to the client through callback.

Native implementation

<! DOCTYPE html> 

The content of test1.php on the server side is as follows:

<?php$arr = [1,2,3,4,5,6];$result = json_encode($arr);echo "jsonpcallback(".$result.")";?>

It should be noted that the final assembled return value content.

Let's take a look at the final code execution result.

JQuery implementation

There are still a lot of things to be processed by using native JavaScript. to simplify the operation, we decided to use jQuery instead.

<! DOCTYPE html> 

Correspondingly, test1.php also made some changes to meet the client's chat needs.

<? Php $ requestparam = isset ($ _ GET ['callback'])? $ _ GET ['callback']: 'callback'; // qingyunzhi chatbot interface: http://api.qingyunke.com/api.php? Key = free & appid = 0 & msg = hello // receive REQUEST content from the client $ talk = $ _ REQUEST ['tal']; $ result = file_get_contents ("http://api.qingyunke.com/api.php? Key = free & appid = 0 & msg = $ talk "); // splice some strings echo $ requestparam." ($ result) ";?>

Finally, let's take a look at the cross-origin effect.

Summary

So far, the simple cross-origin problem of ajax is almost solved. For me, I have some opinions on these three methods.

  1. The Access-Control-Allow-Origin method is applicable to small applications or personal applications with high credit requirements.
  2. The proxy mode is suitable for processing large applications. However, a unified specification is required to facilitate management and maintenance.
  3. The JSONP method is still quite tasteless (it may be that my experience is insufficient. I didn't realize the advantages of this method (⊙) B ). You know you have something to do. It is really advantageous to maintain.

Reference link:

Ajax cross-origin request: http://www.bkjia.com/article/72703.htm

Server-side cross-origin settings: http://www.bkjia.com/article/104442.htm

Ajax advanced notes: http://www.bkjia.com/article/116878.htm

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.