Ajax跨網域存取Cookie遺失問題的解決方法_AJAX相關

小云云
發布: 2023-03-19 11:24:01
原創
2409 人瀏覽過

本ajax跨域訪問,可以使用jsonp方法或設定Access-Control-Allow-Origin實現,關於設定Access-Control-Allow-Origin實現跨域訪問可以參考之前我寫的文章《ajax 設定Access-Control -Allow-Origin實現跨域訪問》文主要介紹了Ajax跨域訪問Cookie丟失問題的解決方法,需要的朋友可以參考下,希望能幫助到大家。

1.ajax跨網域存取,cookie遺失

首先建立兩個測試網域

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

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

測試程式碼

setcookie.PHP 用於設定服務端cookie

<?php
setcookie(&#39;data&#39;, time(), time()+3600);
?>
登入後複製

server.php 用於被客戶端請求

<?php
$name = isset($_POST[&#39;name&#39;])? $_POST[&#39;name&#39;] : &#39;&#39;;
$ret = array(
 &#39;success&#39; => 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[&#39;name&#39;])? $_POST[&#39;name&#39;] : &#39;&#39;;
$ret = array(
 &#39;success&#39; => 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");
登入後複製
相關推薦:

JS實作Ajax跨域請求flask回應內容

Ajax跨域請求COOKIE無法帶上的完美解決方案

實例詳解Ajax跨域請求的原理#

以上是Ajax跨網域存取Cookie遺失問題的解決方法_AJAX相關的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!