简体   繁体   English

如何修复TypeError:undefined不是对象错误?

[英]How to fix TypeError: undefined is not an object error?

I'm trying to add results of a file got using XMLHttpRequest to an array. 我试图将使用XMLHttpRequest获得的文件的结果添加到数组中。 The file is a json. 该文件是一个json。

Here's a Code that creates the error: 这是一个创建错误的代码:

var array = [];
var req = new XMLHttpRequest();
req("get", "test.json");
req.onreadystatechange = handle(req, array);
req.send();

function handle(req, array) {
    if ((req.target.readyState == 4) && (req.target.status == 200)) {
        var json = JSON.parse(req.target.responseText);
        array.push(json.test);
        alert(array);

    }
}

Without using target is has the value 4 不使用target的值为4

You have used wrong property of request. 您使用了错误的请求属性。

Try with inline function for onreadystatechange callback 尝试使用内联函数进行onreadystatechange回调

var array = [];
var req = new XMLHttpRequest();
req("get", "test.json");
req.onreadystatechange = function(){
     if ((req.readyState == 4) && (req.status == 200)) {
        var json = JSON.parse(req.responseText);
        array.push(json.test);
        alert(array);
    }
};
req.send();

or as per your way 或按照你的方式

var array = [];
    var req = new XMLHttpRequest();
    req("get", "test.json");
    req.onreadystatechange = handle();
    req.send();
function handle(){
         if ((req.readyState == 4) && (req.status == 200)) {
            var json = JSON.parse(req.responseText);
            array.push(json.test);
            alert(array);
        }
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在导入期间修复“ TypeError:未定义不是对象” - How to fix 'TypeError: undefined is not an object' during import 如何修复“TypeError: undefined is not an object”? - How can I fix 'TypeError: undefined is not an object'? 我该如何修复此错误错误类型错误:未定义不是 object(正在评估“userData.username”) - How can i fix this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') 如何修复“TypeError:_this is undefined” - How to fix “TypeError: _this is undefined” 整数到字符串,我该如何解决以下错误:“TypeError: Can't convert undefined to object”? - Integer to String, How can I fix the following error: "TypeError: Can't convert undefined to object"? TypeError:未定义不是对象错误 - TypeError: undefined is not an object error 如何修复 TypeError: undefined is not an object(评估“state.routes”) - How to fix TypeError: undefined is not an object (evaluating 'state.routes') 如何修复错误“错误类型错误:无法读取未定义的属性‘0’” - how to fix the error "ERROR TypeError: Cannot read property '0' of undefined" 如何修复Javascript中的“未定义不是对象”错误 - How to fix “Undefined is not an object” error in Javascript 如何修复native native中的'undefined is not object'错误 - How to fix 'undefined is not an object' error in react native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM