我在我的网站上得到了一个注册页面,问题是我开始得到这个错误:
Uncaught TypeError: Cannot read property 'responseText' of undefined
拒绝设置不安全的header "Content-length" register.php:1
拒绝设置不安全的报头"Connection"
即使没有最后两个错误(如果我没有设置连接,内容长度报头),我也会得到第一个错误
对于我的ajax功能,我使用这个函数:
function AjaxLoad(xhr, url, cfunc, syn, method, headers, params)
{
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = cfunc; // This line take place on true/false
xhr.open(method, url, syn);
$.each(headers ,function(index, value){
xhr.setRequestHeader(index, value);
});
xhr.send(params);
}
在我的js代码,我调用函数如下:
var headersObject = {"Content-type" : "application/x-www-form-urlencoded", "Content-length" : userCap.val().length, "Connection" : "close" };
AjaxLoad(
xhr,
"../php/Ajax/captchaValidator.php",
getResponse,
false,
"POST",
headersObject,
userCap.attr("name") + "=" + encodeURIComponent(userCap.val())
);
AjaxLoad参数解释:
- <
- xhr对象/gh>
- <
- onreadystatechange处理器/gh>
- 同步(它不工作,即使我将传递true)
- <
- 头/gh>
- key=value对(我确实测试了它,所以它得到正确的值)
这是getResponse函数
function getResponse(){ var strongEl = capCon.next(); if(xhr.responseText == "0"){ if(strongEl.prop("tagName") == "STRONG"){ strongEl.getReplace('<strong id="sE">קוד שגוי</strong>'); }else{ capCon.after('<strong id="sE">קוד שגוי</strong>').next(); } bToSubmit = false; }else{ if(strongEl.prop("tagName") == "STRONG"){ strongEl.remove(); } } }
我测试网络,看看文件captchaValidator.php是否甚至到达浏览器,我得到状态200,一切似乎ok。
我做了正确的值测试,代码工作之前我不知道有什么变化,但这是链接到我的网站注册页面链接,如果你按发送,你可以看到(在chrome浏览器在网络选项卡),一切都很好,但我得到我在控制台选项卡提到的错误,如果有人可以请看看我将非常感谢。
如错误所示,xhr
变量未定义。快速浏览一下getResponse
函数,您可以看到它可能不在作用域中。作为AjaxLoad
参数的一个是该函数的局部(顺便说一句,将其作为参数似乎非常无用,因为您要做的第一件事就是分配给它),而您在调用中作为参数传递的一个可能是undefined
或来自不同的作用域。
相反,您可以使用this
关键字从事件处理程序访问当前的XMLHttpRequest
对象。将代码更改为
if (this.responseText == "0"){
如果你想使用ajax和jQuery,使用$.ajax
和朋友:
$.post(
"../php/Ajax/captchaValidator.php",
userCap.attr("name") + "=" + encodeURIComponent(userCap.val()),
function(responseData) {
//...
}
)
你的代码不工作,因为变量xhr
不在getResponse
的范围内。您可以在事件处理程序中使用this
而不是xhr
来引用XHR对象。