第一次的写法:
function Exists(url) { $.ajax({ url: url, type: 'HEAD', error: function () { //file not exists console.info("file not exists "); return false; }, success: function () { //file exists console.info("file exists"); return true; } }); }通过ajax调用的方式,如果没错,则返回true,否则返回false。打算的很好,但是Exists(url)无论在console.info输出file exists还是file not exists的情况下,始终是undefinded。
最后只能归结为$.ajax调用的时候这个return返回值返回不到外部的函数调用。于是进行了修改,修改后的代码如下:
function Exists(url) { var isExists; $.ajax({ url: url, type: 'HEAD', error: function () { //file not exists console.info("file not exists "); isExists = 0; }, success: function () { //file exists console.info("file exists"); isExists = 1; } }); console.info("isexists:" + isExists); if (isExists == 1) { return true; } else { return false; } }这个写法用文件不存在的url进行测试,浏览器console面板输出如下:
isexists:undefined
file not exists
这个写法用文件存在的url进行测试,浏览器console面板输出如下:
isexists:undefined
file exists
仔细查看输出发现先输出isexists,后输出文件是否存在。我们知道程序代码都是顺序执行的,通常意味着应该先输出file exists或file not exists,后输出isexists。出现这个是
什么原因?仔细想想,就知道了,问题出在异步调用。在执行这个函数的时候,异步调用isexists还没有值,导致始终是undefinded。知道了这个再次改写代码为同步调用:
function Exists(url) { var isExists; $.ajax({ url: url, async:false, type: 'HEAD', error: function () { //file not exists console.info("file not exists "); isExists = 0; }, success: function () { //file exists console.info("file exists"); isExists = 1; } }); console.info("isexists:" + isExists); if (isExists == 1) { return true; } else { return false; } }这个时候 function Exists ( url ) 函数能够根据文件是否存在回归正确的true或false.
既然是异步调用导致的这个问题,我第一次的写法增加同步调用写法是否能得到正确的值呢。增加代码进行测试:
测试结果 function Exists ( url )仍然是始终为undefined。function Exists(url) { $.ajax({ url: url, async:false, type: 'HEAD', error: function () { //file not exists console.info("file not exists "); return false; }, success: function () { //file exists console.info("file exists"); return true; } }); }
得到两个经验:
其一,如果$.ajax在函数中调用根据结果返回true或false是不可行的
其二,如果函数必须有返回值,则返回值需要在$.ajax外面定义,然后根据$.ajax得到不同的值,并且$.ajax需要使用同步模式,不能使用异步模式