代码之家  ›  专栏  ›  技术社区  ›  localhost

XHR调用返回空

  •  0
  • localhost  · 技术社区  · 8 年前

    我是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 回复  |  直到 8 年前
        1
  •  1
  •   ZombieChowder    8 年前

    在你的请求中有几件事要注意。

    1. 你需要添加 status 到 200 因为它是 好啊 状态。也就是说你的请求已经通过了。所以那部分会变成 (this.readyState == 4 && this.status == 200) .

    2. 你还需要改变使用三等号 === 到 == 因为你没有比较 类型 因为js中使用了三等号。

    3. 使用事件处理程序 xhttp.onreadystatechange 而不是 xmr.readySate . 这里是一个 link to the Mozilla documentation .

    所以它应该变成:

    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 .

        2
  •  0
  •   Rajender Joshi    8 年前

    你需要 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();
    
        3
  •  0
  •   iStepashka    8 年前

    应该使用xhr.onreadystatechange而不是xhr.readystate 像这样: xhr.onreadystatechange=函数(){

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

    }