Home >Web Front-end >JS Tutorial >Ajax cross-domain request cannot use cookies

Ajax cross-domain request cannot use cookies

php中世界最好的语言
php中世界最好的语言Original
2018-04-02 09:18:061388browse

This time I will bring you the Ajax cross-domain request that fails to reach the cookie, and solve the problem of the Ajax cross-domain request that fails to reach the cookie. What are the precautions?The following is a practical case, let's take a look.

1. Native ajax request method:

1 var xhr = new XMLHttpRequest();

2 xhr.open ("POST", "http://xxxx.com/demo/b/index.php", true);

3 xhr.withCredentials = true; //Support cross-domain sending cookies

4 xhr.send();

2. Ajax post method request of jquery:

$.ajax({
    type: "POST",
    url: "http://xxx.com/api/test",
    dataType: 'json',
    // 允许携带证书
    xhrFields: {
       withCredentials: true
    },
    // 允许跨域
    crossDomain: true,
    success:function(){
    },
    error:function(){
  }
})

3. Server-side settings:

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://www.xxx.com");

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese Other related articles online!

Recommended reading:

Implementing Ajax Submit to prompt the user when uploading files

Methods for ajax front-end and back-end interaction

The above is the detailed content of Ajax cross-domain request cannot use cookies. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn