Ajax and cookies

Ajax and cookies

本文关键字:cookies and Ajax      更新时间:2023-09-26

我不是一个太多的web开发人员,所以这可能是一个新手的问题。

我正在尝试做xml请求,我发送用户名和密码。在回复中,我的服务器应用程序将在响应头中粘贴一个cookie。是否可以使用文档访问此cookie。饼干变量?

可以,只要cookie没有设置HttpOnly标志。

是的,你绝对可以。我编写了一个程序来测试它。

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); 
?>