Ajax implements API interface calls across domains

Source: Internet
Author: User

Background: You want to implement a cross-domain call interface, and then support the next call, with the ability to bring cookie information, and support cross-domain invocation of domain names from multiple sources.

1. This supports cross-domain calls from all domain names:

Cross-domain is not supported, browser error:

Add the appropriate protocol header to the API interface server:

Header ("Access-control-allow-origin: *",); Header (' Access-control-allow-headers:x-requested-with, Content-type ');

However, such API interfaces do not support cookies.

2. If you want to support cookies, you need to add

Header (' access-control-allow-credentials:true ');

However, in this case, the front of the server set the header, the browser will be error. Say it's access-control-allow-origin head. * This wildcard is not available.

Header ("Access-control-allow-origin: *",);

Browser error such as:

  

Must be changed to a specific domain name. However, our API also want to support the cross-domain access from many different domain names, how to do it, at this time, the server to do a dynamic judgment processing is OK.

<?php$ret = Array (    ' name ' = isset ($_post[' name '])? $_post[' name ']: ',    ' gender ' = isset ($_post[') Gender '])? $_post[' gender '): Header (' Content-type:application:json;charset=utf8 '); $origin = Isset ($_server[' Http_origin ') ])? $_server[' http_origin ': '; $allow _origin = Array (    ' http://www.client.com ',    ' http://www.client2.com '); if ( In_array ($origin, $allow _origin)) {    header (' Access-control-allow-origin: '. $origin);    Header (' Access-control-allow-methods:post ');    Header (' Access-control-allow-headers:x-requested-with,content-type ');} echo Json_encode ($ret);? >

Reference: http://my.oschina.net/blogshi/blog/303758

Ajax implements API interface calls across domains

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.