在下面的代码中,我所要做的就是从jQuery中获取HTTP响应代码。ajax调用。然后,如果代码是301(永久移动),显示'Location'响应头:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>jQuery 301 Trial</title>
<script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
function get_resp_status(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
// if (response code is 301) {
console.log ("Location: " + jqxhr.getResponseHeader("Location"));
// }
}
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$('a').mouseenter(
function () {
get_resp_status(this.href);
},
function () {
}
);
});
</script>
</head>
<body>
<a href="http://ow.ly/4etPl">Test 301 redirect</a>
<a href="http://cnn.com/not_found">Test 404 not found</a>
</body>
</html>
有人能指出我哪里错了吗?当我检查Firebug中的'jqxhr'对象时,我找不到状态码,也找不到'Location'响应头。我在“完成”的最后一行设置了断点。
谢谢。
你可以检查你的响应内容,只要console.log它,你会看到哪个属性有一个状态码。如果你不明白jsons的意思,请参考视频:https://www.youtube.com/watch?v=Bv_5Zv5c-Ts
它解释了非常基本的知识,让你更舒服地使用javascript。
你可以用ajax请求的短版本来做,请参阅上面的代码:
$.get("example.url.com", function(data) {
console.log(data);
}).done(function() {
// TO DO ON DONE
}).fail(function(data, textStatus, xhr) {
//This shows status code eg. 403
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+xhr);
}).always(function() {
//TO-DO after fail/done request.
console.log("ended");
});
示例控制台输出:
error 403
STATUS: Forbidden
ended
我看到了jqXhr对象上的状态字段,这里是一个摆弄它的工作:
http://jsfiddle.net/magicaj/55HQq/3/
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
你可以检查你的响应内容,只要console.log它,你会看到哪个属性有一个状态码。如果你不明白jsons的意思,请参考视频:https://www.youtube.com/watch?v=Bv_5Zv5c-Ts
它解释了非常基本的知识,让你更舒服地使用javascript。
你可以用ajax请求的短版本来做,请参阅上面的代码:
$.get("example.url.com", function(data) {
console.log(data);
}).done(function() {
// TO DO ON DONE
}).fail(function(data, textStatus, xhr) {
//This shows status code eg. 403
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+xhr);
}).always(function() {
//TO-DO after fail/done request.
console.log("ended");
});
示例控制台输出:
error 403
STATUS: Forbidden
ended