Javascript 使用javascript检查http状态码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8571227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use javascript to check http status codes
提问by Deepak Mittal
I want to display profile pictures from gravatar for only those users who have a picture set. Doing this server side means doing around 100 HEAD requests to gravatar for checking 404 codes and appropriately outputting img
tags for each request.
我只想为拥有图片集的用户显示来自gravatar 的个人资料图片。做这个服务器端意味着向 gravatar 发送大约 100 个 HEAD 请求,以检查 404 代码并img
为每个请求适当地输出标签。
So, I want to implement a javascript function where I can just output 100 urls for which javascript can check the http status codes and output the appropriate image tags dynamically. Is that even possible? How?
所以,我想实现一个 javascript 函数,我可以只输出 100 个 url,javascript 可以检查 http 状态代码并动态输出适当的图像标签。这甚至可能吗?如何?
回答by Shalom Craimer
The keyword you're missing is "status code" (that's what we collectively call all the HTTP response codes of 200, 404, 500, etc). I'm going to assume you're using jQuery, in which case, all the documentation you need for doing AJAX is at http://api.jquery.com/jQuery.ajax/
您缺少的关键字是“状态代码”(这就是我们统称为 200、404、500 等的所有 HTTP 响应代码)。我将假设您使用的是 jQuery,在这种情况下,执行 AJAX 所需的所有文档都位于http://api.jquery.com/jQuery.ajax/
Here's a simple example for a request that displays an alert, but only if a 404 status code is returned (lifted almost verbatim the link above):
这是一个显示警报的请求的简单示例,但前提是返回 404 状态代码(几乎逐字解除了上面的链接):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
var url = "some_url";
$.ajax(url,
{
statusCode: {
404: function() {
alert('page not found');
}
}
});
});
</script>