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

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

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供威信網(wǎng)站建設(shè)、威信做網(wǎng)站、威信網(wǎng)站設(shè)計(jì)、威信網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、威信企業(yè)網(wǎng)站模板建站服務(wù),十余年威信做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。

1.ajax跨域訪問,cookie丟失

首先創(chuàng)建兩個測試域名

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

b.fdipzone.com 作為服務(wù)端域名

測試代碼

setcookie.PHP 用于設(shè)置服務(wù)端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');
// 響應(yīng)類型
header('Access-Control-Allow-Methods:POST'); 
// 響應(yīng)頭設(shè)置
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>

首先先執(zhí)行http://b.fdipzone.com/setcookie.php, 創(chuàng)建服務(wù)端cookie。

然后執(zhí)行http://a.fdipzone.com/test.html

輸出

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

獲取cookie失敗。

2.解決方法

客戶端

請求時將withCredentials屬性設(shè)置為true

使可以指定某個請求應(yīng)該發(fā)送憑據(jù)。如果服務(wù)器接收帶憑據(jù)的請求,會用下面的HTTP頭部來響應(yīng)。

服務(wù)端

設(shè)置header

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

允許請求帶有驗(yàn)證信息

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}, // 發(fā)送憑據(jù)
   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');
// 響應(yīng)類型
header('Access-Control-Allow-Methods:POST'); 
// 響應(yīng)頭設(shè)置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
// 是否允許請求帶有驗(yàn)證信息
header('Access-Control-Allow-Credentials:true');
header('content-type:application/json');
echo json_encode($ret);
?>

按之前步驟執(zhí)行,請求返回

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

獲取cookie成功

3.注意事項(xiàng)

1.如果客戶端設(shè)置了withCredentials屬性設(shè)置為true,而服務(wù)端沒有設(shè)置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.服務(wù)端header設(shè)置Access-Control-Allow-Credentials:true后,Access-Control-Allow-Origin不可以設(shè)為*,必須設(shè)置為一個域名,否則回返回錯誤。

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; //支持跨域發(fā)送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(){
 }
})

服務(wù)器端設(shè)置:

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

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

分享題目:如何解決Ajax跨域訪問Cookie丟失問題
文章地址:http://muchs.cn/article36/jpggpg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、微信公眾號、、企業(yè)網(wǎng)站制作、網(wǎng)站維護(hù)軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司