[英]How to cleanly get a text file using AJAX request
請參見下面的代碼。 發送請求並返回確定后,在reqListener()
函數中,我獲得了文本文件輸出的內容。
但是,當我稍后嘗試返回響應變量時,它仍然是未定義的,就好像尚未調用reqListener()
。 這可能是由於async=true
參數引起的嗎?
此外,是否有更巧妙的方法可以使請求成功(例如使用閉包)從功能中獲取響應文本?
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);
該請求將需要一些時間才能完成。 您最好提供一個在文件加載后觸發的回調:
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.