如何返回到调用当前函数的函数
How to return to the function calling the current function
如何返回到调用函数(上面的函数)。如果在执行UrlExists('file.png')
:时文件存在,我希望返回true
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, true);
http.onerror = function(e){
//console.log('......onerror: ' + JSON.stringify(e));
if (typeof e !== 'undefined'){
return false
}
};
http.send();
return http.onerror();
}
使用XMLHttpResponse作为异步。由于异步响应可能不会按照请求的顺序接收,而且您可能正在检查多个文件,因此在处理文件不"存在"(未找到或返回错误等)的情况之前,最好检查responseURL
属性。
jsFiddle示例:http://jsfiddle.net/5f42L6nz/4/
来源:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
function UrlExists(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true); // true => async request
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// URL found, do stuff for "exists"
alert("url exists:'r'n" + xhr.responseURL);
} else {
// URL not found, could check xhr.status === 404, etc.
// do stuff when URL not found, but no exception/error thrown
alert("not found or unexpected response:'r'n" + xhr.responseURL);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");
相关文章:
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用