如何使用AJAX请求得到清晰的文本文件如何使用、文本文件、清晰、AJAX

2023-09-10 18:32:06 作者:被自己绑架丶

请参阅下面的code。当请求被发送,回来好了,在 reqListener()功能,我让我的文本文件输出的内容。

然而,当我尝试响应变量返回后,它仍然是不确定的,仿佛 reqListener()还没有叫呢。难道这是由于异步=真参数?

此外,有没有更合适的方法来获取响应文本输出的功能应该是请求是成功的,就像使用封闭?

 函数load_text_file()
{
    功能reqListener(){
        如果(this.readyState == 4和&安培; this.status == 200)
        {
                响应= this.responseText;
                的console.log(响应);
        }
    }

    VAR响应;
    VAR oReq =新XMLHtt prequest();
    oReq.onreadystatechange = reqListener;
    oReq.open(得,file.txt的,真正的);
    oReq.send();
    返回响应;
}

变种TEXT = load_text_file();
执行console.log(文字);
 

解决方案

该请求将需要一段时间才能完成。你会在回调而触发时,该文件已加载更好移交:

 函数load_text_file(回调)
{

    功能reqListener(){

        如果(this.readyState == 4和&安培; this.status == 200)
        {
                的console.log(响应);
                回调(this.responseText);

        }
    }


    VAR oReq =新XMLHtt prequest();
    oReq.onreadystatechange = reqListener;
    oReq.open(得,file.txt的,真正的);
    oReq.send();
}

load_text_file(函数(){
    执行console.log(文字);
});
 
用ajax怎么获取文件

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.

However, when I try to return the response variable later, it's still undefined, as if reqListener() hasn't been called yet. Could this be due to the async=true argument?

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);
});