溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解決Ajax跨域訪問Cookie丟失問題

發布時間:2021-06-29 15:22:27 來源:億速云 閱讀:174 作者:小新 欄目:web開發

這篇文章將為大家詳細講解有關如何解決Ajax跨域訪問Cookie丟失問題,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

1.ajax跨域訪問,cookie丟失

首先創建兩個測試域名

a.fdipzone.com 作為客戶端域名

b.fdipzone.com 作為服務端域名

測試代碼

setcookie.PHP 用于設置服務端cookie

<?php
setcookie('data', time(), time()+3600);
?>

server.php 用于被客戶端請求

<?php
$name = isset($_POST['name'])? $_POST['name'] : '';
$ret = array(
 'success' => true,
 'name' => $name,
 'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : ''
);
// 指定允許其他域名訪問
header('Access-Control-Allow-Origin:http://a.fdipzone.com');
// 響應類型
header('Access-Control-Allow-Methods:POST'); 
// 響應頭設置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('content-type:application/json');
echo json_encode($ret);
?>

test.html 客戶端請求頁面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 <title> ajax 跨域訪問cookie丟失的解決方法 </title>
 </head>
 <body>
 <script type="text/javascript">
 $(function(){
  $.ajax({
   url: 'http://b.fdipzone.com/server.php', // 跨域
   dataType: 'json',
   type: 'post',
   data: {'name':'fdipzone'},
   success:function(ret){
    if(ret['success']==true){
     alert('cookie:' + ret['cookie']);
    }
   }
  });
 })
 </script>
 </body>
</html>

首先先執行http://b.fdipzone.com/setcookie.php, 創建服務端cookie。

然后執行http://a.fdipzone.com/test.html

輸出

{"success":true,"name":"fdipzone","cookie":""}

獲取cookie失敗。

2.解決方法

客戶端

請求時將withCredentials屬性設置為true

使可以指定某個請求應該發送憑據。如果服務器接收帶憑據的請求,會用下面的HTTP頭部來響應。

服務端

設置header

header("Access-Control-Allow-Credentials:true");

允許請求帶有驗證信息

test.html 修改如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 <title> ajax 跨域訪問cookie丟失的解決方法 </title>
 </head>
 <body>
 <script type="text/javascript">
 $(function(){
  $.ajax({
   url: 'http://b.fdipzone.com/server.php', // 跨域
   xhrFields:{withCredentials: true}, // 發送憑據
   dataType: 'json',
   type: 'post',
   data: {'name':'fdipzone'},
   success:function(ret){
    if(ret['success']==true){
     alert('cookie:' + ret['cookie']);
    }
   }
  });
 })
 </script>
 </body>
</html>

server.php 修改如下

<?php
$name = isset($_POST['name'])? $_POST['name'] : '';
$ret = array(
 'success' => true,
 'name' => $name,
 'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : ''
);
// 指定允許其他域名訪問
header('Access-Control-Allow-Origin:http://a.fdipzone.com');
// 響應類型
header('Access-Control-Allow-Methods:POST'); 
// 響應頭設置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
// 是否允許請求帶有驗證信息
header('Access-Control-Allow-Credentials:true');
header('content-type:application/json');
echo json_encode($ret);
?>

按之前步驟執行,請求返回

{"success":true,"name":"fdipzone","cookie":"1484558863"}

獲取cookie成功

3.注意事項

1.如果客戶端設置了withCredentials屬性設置為true,而服務端沒有設置Access-Control-Allow-Credentials:true,請求時會返回錯誤。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://a.fdipzone.com' is therefore not allowed access.

2.服務端header設置Access-Control-Allow-Credentials:true后,Access-Control-Allow-Origin不可以設為*,必須設置為一個域名,否則回返回錯誤。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' heade

下面看下Ajax跨域請求COOKIE無法帶上的解決辦法

原生ajax請求方式:

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "http://xxxx.com/demo/b/index.php", true); 
xhr.withCredentials = true; //支持跨域發送cookies
xhr.send();

jquery的ajax的post方法請求:

 $.ajax({
    type: "POST",
    url: "http://xxx.com/api/test",
    dataType: 'jsonp',
    xhrFields: {
      withCredentials: true
    },
   crossDomain: true,
   success:function(){
  },
   error:function(){
 }
})

服務器端設置:

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

關于“如何解決Ajax跨域訪問Cookie丟失問題”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女