2011-12-05 3 views
0

너무 많은 웹 개발자가 아니기 때문에 이것은 초보자 용 질문 일 수 있습니다.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 플래그가 설정되지 않은 한.