检查JavaScript中是否存在服务器端文件

Ota*_*our -1 javascript php ajax jquery

我想编写一个在客户端使用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;
}
Run Code Online (Sandbox Code Playgroud)

问题是,由于Ajax是异步的,fileAlreadyExists因此通常undefined在Ajax块设置之前返回(as ).

T.J*_*der 5

使用回调或您自己的回调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
    }); 
}
Run Code Online (Sandbox Code Playgroud)

用法:

ROIFileExists(function(exists) {
    console.log("Exists? " + exists);
});
Run Code Online (Sandbox Code Playgroud)

这是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
}
Run Code Online (Sandbox Code Playgroud)

用法:

ROIFileExists().done(function(exists) {
    console.log("Exists? " + exists);
});
Run Code Online (Sandbox Code Playgroud)

我强烈建议不要使用async: false.它会导致糟糕的用户体验,在通话过程中锁定浏览器的UI; 它将在未来版本的jQuery中消失(你必须XMLHttpRequest自己使用); 你不能使用async: false,如果你有类似的需求,但是当你使用JSONP.

浏览器上的JavaScript代码无论如何都是事件驱动的,因此拥抱事件驱动的本质(在这种情况下,事件是你获得有关文件的信息)通常是要走的路.