首頁  >  文章  >  web前端  >  Ajax跨域訪問時Cookie遺失怎麼解決

Ajax跨域訪問時Cookie遺失怎麼解決

php中世界最好的语言
php中世界最好的语言原創
2018-04-02 16:05:271728瀏覽

這次給大家帶來Ajax跨域訪問時Cookie丟失怎麼解決,解決Ajax跨域訪問時Cookie丟失的注意事項有哪些,下面就是實戰案例,一起來看一下。

ajax跨域訪問,可以使用jsonp方法或設定Access-Control-Allow-Origin實現,關於設定Access-Control-Allow-Origin實現跨域訪問可以參考之前我寫的文章《ajax 設定Access -Control-Allow-Origin實作跨網域存取》

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");
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

用Ajax實作註冊與頭像上傳功能

使用ajax實作分頁技術的步奏詳解(附程式碼)

在Ajax的請求中async:false與async:true有什麼區別
#

以上是Ajax跨域訪問時Cookie遺失怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn