Ajax sets Access-Control-Allow-Origin to implement cross-Origin Access

Source: Internet
Author: User
: This article mainly introduces how to set Access-Control-Allow-Origin in ajax to implement cross-Origin Access. if you are interested in PHP tutorials, refer to it. Cross-origin access through ajax is an old problem. There are many solutions, and the JSONP method is commonly used. the JSONP method is an unofficial method and only supports the GET method, it is not as secure as POST.

Even if jquery's jsonp method is used and type is set to POST, it is automatically changed to GET.

Official question description:

"Script": Evaluates the response as JavaScript and returns it as plain text. disables caching by appending a query string parameter, "_ = [TIMESTAMP]", to the URL unless the cache option is set to true. note: This will turn POSTs into GETs for remote-domain requests.

If the POST method is used for cross-origin, you can create a hidden iframe. this is the same as uploading an image through ajax, but it is troublesome.

Therefore, it is easy to implement cross-Origin Access by setting Access-Control-Allow-Origin.

For example, the domain name of the client is www.client.com, and the requested domain name is www.server.com.

If you directly use ajax for access, the following error occurs:

XMLHttpRequest cannot load http://www.server.com/server.php. No 'access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // www.client.com 'is therefore not allowed Access.

Add in the requested Response header

// Specify to allow access by other domain names

Header ('Access-Control-Allow-Origin :*');

// Response type

Header ('Access-Control-Allow-Methods: Post ');

// Response header settings

Header ('Access-Control-Allow-Headers: x-requested-with, content-type ');

You can implement cross-origin access to ajax POST.

The code is as follows:

Client.html path: http://www.client.com/client.html

   
   Cross-origin testing  

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.