有人能用javascript解释一下下面的代码吗;它用于读取文本文件,但我不';我不知道XML和AJAX的东西?
我试图读取一个文本文件,我的代码完全可以工作。问题是我不理解代码,尤其是所有的有人能用javascript解释一下下面的代码吗;它用于读取文本文件,但我不';我不知道XML和AJAX的东西?,javascript,jquery,ajax,explain,Javascript,Jquery,Ajax,Explain,我试图读取一个文本文件,我的代码完全可以工作。问题是我不理解代码,尤其是所有的onreadystatechange和newxmlhttprequest()和状态的东西-我非常非常困惑 //load text file, and split each word into an array function loadwords(myfile){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", myfile, fa
onreadystatechange
和newxmlhttprequest()代码>和状态
的东西-我非常非常困惑
//load text file, and split each word into an array
function loadwords(myfile){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", myfile, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
//the file is read and stored into a variable
var Text;
Text = rawFile.responseText;
thewords= Text.split("\n");
//The variable Text has a string data type.
//So the string is split into an array.
//Each line being the form of separation between each element
var i;
for (i in thewords){
if ( thewords[i] == "") {
thewords.splice(i,1);
}
}
//The for loop checks for any empty spaces in the array.
//Then removes them from the array using the splice method.
}
}
}
rawFile.send(null);
return thewords;
}
提前非常感谢 在XLMHttpRequest上查看此文档
AJAX代表“异步Javascript和XML”
虽然现在我们主要是在json中使用它
当您发出一个新的XMLHttpRequest时,您正在设置一个新的http请求。“open”方法是添加方法和url的地方。打开请求后,可以通过添加头等方式开始设置。。最后,您“发送”请求。这实际上启动了请求
readyState阻塞表示“当此请求的状态更改时”。
4当请求完成并收到响应时,恰好是最后一个请求。状态是指在响应
中从您刚刚点击的任何服务器发回的HTTP状态代码
你可以在这里看看
上面的代码基本上只是说
嘿,我有个要求。它要去这个地方。如果我得到一个回应,而这个回应不是一个坏的回应,那么就用它做点什么
还值得注意的是,当您返回底部的单词时,您将得到“undefined”。那是因为它还不存在。“send”方法和“return”语句之间的时间非常短,以至于我们的请求可能还没有到达服务器。老实说,它可能还没有在这一点上发送。这是异步编程。要处理它,您应该传递回调,并在回调中处理它。你也可以使用承诺。下面是一个带有回调的实现
function loadwords(myfile, callback){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", myfile, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
return callback(rawFile.responseText);
}
}
}
// You can send data here, or pass nothing
return rawFile.send();
}
function handler(text) {
var thewords= text.split("\n");
//The variable Text has a string data type.
//So the string is split into an array.
//Each line being the form of separation between each element
var i;
for (i in thewords){
if ( thewords[i] == "") {
thewords.splice(i,1);
}
}
}
loadWords('someFile', handler);