我在进行AJAX调用以登录用户时遇到了问题。代码如下所示:
function loginUser()
{
var xmlhttp;
if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//alert(xmlhttp.responseText);
var responseString = xmlhttp.responseText;
if(responseString.indexOf("loginStatus:approved") != -1) {
document.getElementById("logInBar").innerHTML = "Welcome " + getCookie("userLoggedOnfn") + " <a href=\"logoutUser.php\">Logout</a>";
}
}
}
var params = "loginUsername=" + document.getElementById("loginUsername").value +
"&loginPassword=" + document.getElementById("loginPassword").value +
"&d=" + new Date().getTime();
//alert(params);
xmlhttp.open("POST", "loginUser.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
//alert("."); //this alert box is needed to make it work if it's asynchronous
}问题是,如果我像这样使用它,它永远不会达到readyState == 4或3。如果我在它到达chrome的调试器中的readyState == 3之前中断js操作,它就会到达readyState == 4。如果我同步地做,它就能工作,或者如果我在最后添加了警告框……就像它需要暂停一下才能到达readyState == 4或其他什么地方...那么我做错了什么呢?
顺便说一句,我需要用纯AJAX来做这件事,因为这是学校的作业……
发布于 2011-11-16 06:16:10
我找到问题了!它在html代码里。
我将登录按钮和文本框放在一个form标记中,当我按下form标记中的按钮时,chrome会自动刷新整个页面。因此,由于页面的重新加载,AJAX调用被搞乱了。
我只是删除了表单标签,问题就解决了。
发布于 2011-11-14 13:00:10
这可能是因为+ getCookie("userLoggedOnfn") +“中的quotas;转义getCookie(\"userLoggedOnfn\"),看看它是如何工作的
从控制台
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"https://stackoverflow.com/questions/8116821
复制相似问题