admin管理员组文章数量:1415467
How can i make this little function "imageExists" return wether the ajax request was successful or not?
function imageExists(path){
$.ajax({
url: path,
type: 'HEAD',
error:
function(){
return false;
},
success:
function(){
return true;
}
});
}
How can i make this little function "imageExists" return wether the ajax request was successful or not?
function imageExists(path){
$.ajax({
url: path,
type: 'HEAD',
error:
function(){
return false;
},
success:
function(){
return true;
}
});
}
Share
Improve this question
edited Apr 12, 2013 at 14:02
franzlorenzon
5,9436 gold badges37 silver badges58 bronze badges
asked Mar 30, 2011 at 22:32
haemsehaemse
4,2936 gold badges31 silver badges42 bronze badges
3 Answers
Reset to default 4You're going to be returning the result of the AJAX call either in the success
function or in the error
function, so whatever function should be called next should be called from that point.
Because an AJAX request is asynchronous (I'd advise not making it a blocking synchronous call), you make the request but don't know when it will return; it'll call you when it returns, so you just need to provide it something to call.
function imageExists(path){
$.ajax({
url: path,
type: 'HEAD',
error:
function(){
iveReturned(false);
},
success:
function(){
iveReturned(true);
}
});
}
function iveReturned(result) {
// code here to do something following AJAX response.
}
I believe you'll have to use synchronous mode and use a separate a variable for storing the return value.
function imageExists(path){
var isSuccess;
$.ajax({
url: path,
type: 'HEAD',
async: false,
error:
function(){
isSuccess = false;
return false;
},
success:
function(){
isSuccess = true;
return true;
}
});
return isSuccess;
}
Create a var to hold the response on a global level, then set async to false. You need to then set that var in the success or error function.
http://api.jquery./jQuery.ajax/
function imageExists(path){
myVar = null;
$.ajax({
url: path,
type: 'HEAD',
error:
function(){
myVar = false;
},
success:
function(){
myVar = true;
},
async: false
});
}
本文标签: javascriptHow can i return a value from a callback function to the callerStack Overflow
版权声明:本文标题:javascript - How can i return a value from a callback function to the caller? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745180903a2646460.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论