使用jQuery
和Ajax
时,我将整个网址传递给ajax的url:
如果URL
不存在(以某种方式),我该如何重定向到来自page not found
内部的ajax
页面? url
通过和.htaccess
文件。
$(document).ready(function() {
$('.link').click(function () {
var parentTag = 'check=checked';
if(parentTag) {
// ajax call
$.ajax({
type:"GET",
url:"/mylink/buyers/1/0/0", //If this failed, how do I redirect to something else from here?
data:parentTag,
dataType: 'json',
beforeSend:function(callBack){
console.log('checked');
},
success: function(callBack){
console.log('Success');
},
error: function(callBack){
console.log('Failed');
},
});
}
return false;
});
});
答案 0 :(得分:2)
只需为404或任何其他statusCode添加HTTP status处理程序即可!
您还可以添加一般错误回调,但使用状态代码方法的优势在于区分服务器的实际404(页面未找到错误)和其他类型的连接问题。
$.ajax({
/* ... */
statusCode: {
404: function() {
// server says: page not found; let's redirect to 404 page
window.location.href = "http://example.com/my/404/page";
}
},
error: function() {
// something else went wrong
alert('An unknown error occurred!');
}
});
答案 1 :(得分:2)
只需将window.location
置于错误回调中:
$(document).ready(function() {
$('.link').click(function () {
var parentTag = 'check=checked';
if(parentTag) {
// ajax call
$.ajax({
type:"GET",
url:"/mylink/buyers/1/0/0", //If this failed, how do I redirect to something else from here?
data:parentTag,
dataType: 'json',
beforeSend:function(callBack){
console.log('checked');
},
success: function(callBack){
console.log('Success');
},
error: function(callBack){
console.log('Failed');
window.location = "http://www.example.com";
},
});
}
return false;
});
});