我想编写一个函数,该函数使用 JavaScript 在客户端运行,但检查服务器端是否存在文件。 我尝试使用Ajax。
function ROIFileExists(){
var fileAlreadyExists=undefined;
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
});
return fileAlreadyExists;
}
问题是,由于Ajax是异步的,fileAlreadyExists
通常在Ajax块设置之前返回(如undefined
(。
使用回调或您自己的Promise
。
下面是回调方法:
function ROIFileExists(callback){
// --------------------^ Accept the function to call back as an arg
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
var fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
callback(fileAlreadyExists);
// ---------^ Call it
});
}
用法:
ROIFileExists(function(exists) {
console.log("Exists? " + exists);
});
以下是Promise
方法:
function ROIFileExists(){
var d = new $.Deferred(); // Create the deferred object
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
var fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
d.resolve(fileAlreadyExists); // <=== Resolve it
});
return d; // <=== Return it
}
用法:
ROIFileExists().done(function(exists) {
console.log("Exists? " + exists);
});
我强烈建议不要使用async: false
.它会导致用户体验不佳,在通话过程中锁定浏览器的 UI;它将在未来版本的jQuery中消失(您必须自己使用XMLHttpRequest
(;如果你有类似的需求,但当你使用 JSONP 时,你不能使用 async: false
。
浏览器上的 JavaScript 代码无论如何都是事件驱动的,因此拥抱事件驱动的性质(在这种情况下,事件是您获取有关文件的信息(通常是要走的路。
您可以使用
async: false
来确保函数返回结果。(注意:async: false
不是最佳的,如果可以更改应用程序的体系结构以支持回调,则应避免
function ROIFileExists(){
var fileAlreadyExists=undefined;
jQuery.ajax({
async: false, // Add this line
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
fileAlreadyExists = (result!==0);
console.log('fileAlreadyExists='+fileAlreadyExists);
});
return fileAlreadyExists;
}
但是,最好使用回调函数。
function ROIFileExists(callback){
jQuery.ajax({
type: "POST",
url: "ROIFileExists.php",
data: { FileName: fileName},
cache: false
}).done(function( result ) {
callback(result!==0);
});
}