简体   繁体   English

如何使用AJAX请求干净地获取文本文件

[英]How to cleanly get a text file using AJAX request

See the code below. 请参见下面的代码。 When the request is sent and comes back OK, in the reqListener() function, I get the contents of my text file output. 发送请求并返回确定后,在reqListener()函数中,我获得了文本文件输出的内容。

However, when I try to return the response variable later, it's still undefined, as if reqListener() hasn't been called yet. 但是,当我稍后尝试返回响应变量时,它仍然是未定义的,就好像尚未调用reqListener() Could this be due to the async=true argument? 这可能是由于async=true参数引起的吗?

Furthermore, is there a neater way to get the response text out of the function should it the request be successful, like using a closure? 此外,是否有更巧妙的方法可以使请求成功(例如使用闭包)从功能中获取响应文本?

function load_text_file()
{
    function reqListener() {
        if (this.readyState == 4 && this.status == 200)
        {
                response = this.responseText;
                console.log(response);
        }
    }

    var response;
    var oReq = new XMLHttpRequest();
    oReq.onreadystatechange = reqListener;
    oReq.open("get", "file.txt", true);
    oReq.send();
    return response;
}

var TEXT = load_text_file();
console.log(TEXT);

The request will take time to complete. 该请求将需要一些时间才能完成。 You would be better off handing in a callback which fires when the file has loaded: 您最好提供一个在文件加载后触发的回调:

function load_text_file(callback)
{

    function reqListener() {

        if (this.readyState == 4 && this.status == 200)
        {
                console.log(response);
                callback(this.responseText);

        }
    }


    var oReq = new XMLHttpRequest();
    oReq.onreadystatechange = reqListener;
    oReq.open("get", "file.txt", true);
    oReq.send();
}

load_text_file(function(){
    console.log(TEXT);
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM