|
|
寂寞的筷子 · 批量二级域名301重定向开发者社区· 2 周前 · |
|
|
闯红灯的牛肉面 · webRequest.onBeforeReq ...· 1 周前 · |
|
|
憨厚的钥匙 · JSP——使用JavaBean时,实现页面跳 ...· 10 小时前 · |
|
|
沉稳的炒饭 · Azure NetApp 文件的 ...· 4 月前 · |
|
|
逆袭的哑铃 · QTextEdit文本编辑器自带方法:_se ...· 1 年前 · |
|
|
心软的松鼠 · 从 0 到 1 ...· 2 年前 · |
|
|
重情义的小马驹 · Oracle触发器用法实例详解 - 墨天轮· 2 年前 · |
|
|
眼睛小的青蛙 · Windows7下移植Qt4.8.4项目到Q ...· 2 年前 · |
在下面的代码中,我要做的就是从jQuery.ajax调用中获取HTTP响应代码。然后,如果代码是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">
<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>
<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’响应头。我在'complete‘的最后一行设置了断点。
非常感谢。
我在jqXhr对象上看到了status字段,下面是它的工作原理:
http://jsfiddle.net/magicaj/55HQq/3/
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
complete: function(xhr, textStatus) {
console.log(xhr.status);
});
当您的XHR请求返回重定向响应(HTTP Status 301、302、303、307)时,
XMLHttpRequest
automatically follows the redirected URL and returns the status code of that URL
。
您可以通过xhr对象的
status
属性获取非重定向状态代码(200、400、500等)。
因此,您无法从
301
、
302
、
303
或
307
请求的响应头中获取重定向位置。
您可能需要更改服务器逻辑以处理重定向,而不是让浏览器处理重定向。一个 example implementation 。
使用传递给$.ajax函数的参数对象的statusCode属性可能更符合jQuery的习惯:
$.ajax({
statusCode: {
500: function(xhr) {
if(window.console) console.log(xhr.responseText);
});
然而,正如 Livingston Samuel 所说,在javascript中捕获301状态码是不可能的。
你可以检查你的回复内容,只需console.log它,你就会看到哪个属性有一个状态代码。如果您不了解json,请参考视频: 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
|
|
寂寞的筷子 · 批量二级域名301重定向开发者社区 2 周前 |
|
|
憨厚的钥匙 · JSP——使用JavaBean时,实现页面跳转的多种方法讲解request.getRequestDispatcher、response.sendRedirect、超链接、forward动作标记_req 10 小时前 |
|
|
重情义的小马驹 · Oracle触发器用法实例详解 - 墨天轮 2 年前 |