XHR调用返回空

时间:2018-06-07 09:29:34

标签: javascript json

我是AJAX的新手,我正在尝试调用我的json文件,但它没有在控制台中返回任何内容。我查看了网络选项卡,xhr状态为200。

const xhr = new XMLHttpRequest();
xhr.readyState = function(){
    if(xhr.readyState === 4){
        console.log(xhr.responseText)
    }
}
xhr.open('GET','data/task.json');
xhr.send();

和task.json是

{
    "jobs": [
        {
            "id": 7,
            "title": "Clerk",
            "employer": {
                "name": "AOL"
            },
            "location": "Floria",
            "salary": "$45k+"
        }
    ]
}

我尝试解析它并使用控制台将其打印出来,但控制台也是空的。

3 个答案:

答案 0 :(得分:1)

您正在制作的请求中需要注意一些事项。

  1. 您需要将status添加到200,因为它是确定状态。意味着您的请求通过。因此该部分将成为(this.readyState == 4 && this.status == 200)

  2. 您还需要使用三等号===更改为==,因为您不是通过 TYPE 进行比较,因为在JS中使用了三等号。

  3. 使用事件处理程序xhttp.onreadystatechange代替xmr.readySate。这是link to the Mozilla documentation

  4. 所以应该成为:

    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange= function(){
        if(xhttp.readyState === 4 && xhttp.status == 200){
            console.log(xhr.responseText)
        }
    }
    xhr.open('GET','data/task.json');
    xhr.send();
    

    以下是W3Schools Documentation with example的详细文档。

答案 1 :(得分:0)

您需要onreadystatechange而不是readyState

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        console.log(xhr.responseText)
    }
}
xhr.open('GET','data/task.json');
xhr.send();

答案 2 :(得分:0)

您应该使用xhr.onreadystatechange而不是xhr.readyState 像那样: xhr.onreadystatechange = function(){

if(xhr.readyState === 4){
    console.log(xhr.responseText)
}

}