OZ1*_*SEJ 5 javascript xmlhttprequest
我正在编写带有javascript的网页,以便根据用户请求从服务器读取文本格式的数据文件.加载文本文件后,我需要稍微操纵一下数据.
我一直在使用XMLHttpRequest进行加载,但是现在我看到同步请求被"弃用"了.我无法在加载数据之前开始操作数据,所以在这种情况下我该怎么办?
T.J*_*der 11
使用一个同步的请求:
function doGET(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// The request is done; did it work?
if (xhr.status == 200) {
// ***Yes, use `xhr.responseText` here***
callback(xhr.responseText);
} else {
// ***No, tell the callback the call failed***
callback(null);
}
}
};
xhr.open("GET", path);
xhr.send();
}
function handleFileData(fileData) {
if (!fileData) {
// Show error
return;
}
// Use the file data
}
// Do the request
doGET("/path/to/file", handleFileData);
Run Code Online (Sandbox Code Playgroud)
或者使用promises,这是处理回调的更现代的方法:
function doGET(path, callback) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// The request is done; did it work?
if (xhr.status == 200) {
// Yes, use `xhr.responseText` to resolve the promise
resolve(xhr.responseText);
} else {
// No, reject the promise
reject(xhr);
}
}
};
xhr.open("GET", path);
xhr.send();
});
}
// Do the request
doGET("/path/to/file")
.then(function(fileData) {
// Use the file data
})
.catch(function(xhr) {
// The call failed, look at `xhr` for details
});
Run Code Online (Sandbox Code Playgroud)
既然你想处理本地文件,试试这个
function readFile(file)
{
var f = new XMLHttpRequest();
f.open("GET", file, false);
f.onreadystatechange = function ()
{
if(f.readyState === 4)
{
if(f.status === 200 || f.status == 0)
{
var res= f.responseText;
alert(res);
}
}
}
f.send(null);
}
Run Code Online (Sandbox Code Playgroud)
然后你必须打电话给File:\\
readFile('File:\\\yourpath');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9268 次 |
最近记录: |