2011-12-05 1 views
0

私はあまりWebデベロッパーではないので、これは初心者の質問かもしれません。Ajaxとクッキー

ユーザー名とパスワードを送信するxmlリクエストを実行しようとしています。応答で私のサーバーアプリケーションは、応答ヘッダーにクッキーを貼り付けます。このクッキーにはdocument.cookie変数を使用してアクセスできますか?

答えて

1

もちろん、間違いなく可能です。私はそれをテストするプログラムを作った。

HTMLファイル:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div { 
    position:relative; 
    left:10px; 
    top:10px; 
    width:100px; 
    height:70px; 
    background-color:#F00; 
} 
</style> 
</head> 
<body> 
<div onclick="sendRequest('cookieset.php')">Click me</div> 
</body> 
<script> 
function sendRequest(address) { 
    var xmlRequest = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); 
    if(xmlRequest == null) { 
     console.log("Error: XMLHttpRequest failed to initiate."); 
    } 

    xmlRequest.onreadystatechange = function() { 
     if (xmlRequest.readyState == 4) { //Completed loading 
      if (xmlRequest.status == 200 || xmlRequest.status == 0) { 
       alert(document.cookie) 
      } 
      else //Otherwise, there was a problem while loading 
       xmlContainer.innerHTML = "Error " + xmlRequest.status + " has occurred."; 
     } 
    } 
    try { 
     xmlRequest.open("GET", address, true); 
     xmlRequest.send(null); 

    } catch(e) { 
     console.log("Error retrieving data file. Some browsers only accept cross-domain request with HTTP."); 
    } 

} 
</script> 

</html> 

PHPファイル:

<?php 
    setcookie("cookieTest", "good", 0); 
?> 
3

はい、クッキーにHttpOnlyフラグが設定されていない限りです。