javascript - 未捕获的类型错误 : Cannot read property 'responseText' of undefined

标签 javascript ajax

我的网站上有一个注册页面,问题是我开始收到此错误:

未捕获的类型错误:无法读取未定义的属性“responseText”

拒绝设置不安全的 header “Content-length” register.php:1

拒绝设置不安全的 header “连接”

即使没有最后两个错误(如果我没有设置连接,内容长度 header ),我也会收到第一个错误。

对于我的 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 对象
  • 位置
  • onreadystatechange 处理程序
  • 同步(即使我通过 true,它也不起作用)
  • 方法
  • 标题
  • 键=值对(我确实对其进行了测试,因此它得到了正确的值)

  • 这是 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 一切似乎都很好。

    我确实测试了正确的值,在我不知道发生了什么变化之前代码确实有效,但这是我的网站注册页面的链接 Link , 如果按 发送 ,您可以看到(在网络选项卡的 chrome 浏览器中)一切正常,但是我在控制台选项卡中收到了我提到的错误,如果有人可以请看一下,我将非常感激。

    最佳答案

    正如错误所说,xhr变量未定义。快速浏览getResponse功能,您可以看到它可能不在范围内。 AjaxLoad 的参数是该函数的本地函数(顺便说一句,将其作为参数似乎毫无用处,因为您要做的第一件事就是分配给它),而您在调用中作为参数传递的可能是 undefined或来自不同的范围。

    相反,您可以访问当前的 XMLHttpRequest来自事件处理程序的对象,带有 this keyword .将您的代码更改为

    if (this.responseText == "0"){
    

    关于javascript - 未捕获的类型错误 : Cannot read property 'responseText' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16874297/

    相关文章:

    javascript - 执行函数时页面刷新/崩溃

    javascript - 将 promise 转换为 Bluebird

    javascript - 发送post请求时无法获取参数

    java - Json 作为 Grails Controller 的参数

    javascript - 从生成的 ID 标记中排除 ContentPlaceHolder

    javascript - 用作谷歌浏览器书签

    javascript - 在 Jquery 中如何处理粘贴?

    javascript - 当服务器和客户端在同一系统上时如何捕获JSON对象

    javascript - ajax jquery 不工作

    php - 使用php从数据库中删除评论