jQuery锚点单击事件会执行ajax发布,重定向后会导致执行错误回调 [英] Jquery anchor tag click event does an ajax post, when it redirects, it causes error callback to execute
问题描述
位于此URL'/main/'上的我的HTML包含以下链接:
My HTML which is at this url '/main/' contains the following link:
<a href="/main/" id="do_something">Do Something</a>
因此,链接应执行某些操作,然后刷新页面.
So, the link should do something and then refresh the page.
我的jquery看起来像这样:
My jquery looks something like this:
$('#do_something').click(function(event) {
var my_values = ['1','2'];
$.ajax({
url:"/process_values/",
type: "POST",
data: {values:my_values},
success:function(response){
alert("success: " + response);
},
error:function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
},
});
});
帖子执行正确,但完成时始终调用错误回调.
The post is executing correctly, but the error callback is always called when it completes.
如果我阻止使用event.preventDefault();调用链接,则执行成功函数.为什么是这样?以及如何在发帖后更新页面?
If I prevent the link from being called using event.preventDefault();, the success function is executed. Why is this? And how do I get the page to update after the post call?
谢谢
推荐答案
如果没有event.preventDefault()
,则将用户定向到/main/
(因为这是锚点的默认行为).卸载页面会导致所有未决的(XmlHttp)请求中止,从而触发error
函数(=请求尚未完成).
Without event.preventDefault()
, the user is directed to /main/
(because it's the default behavior of an anchor). Unloading the page causes all pending (XmlHttp) requests to abort, thus triggering the error
function (=request has not finished yet).
概述:
- 点击
#do_something
- 触发
click
事件-> Ajax请求 - 跟随链接到
/main/
. - 页面卸载->取消所有请求
- XHR中止了->
error
函数已触发
- click
#do_something
- fires
click
event -> Ajax request - follows link to
/main/
. - page unloads -> Cancel all requests
- XHR aborted ->
error
function triggered
如果您想打开页面,请在success
函数中添加它:
If you want the page to open, add this at the success
function:
location.href = "/main/";
或者,如果您不想对链接进行硬编码:
Alternatively, if you don't want to hard-code the link:
$('#do_something').click(function(event) {
event.preventDefault();
var linkTo = $(this).attr("href");
var my_values = ['1','2'];
$.ajax({
url:"/process_values/",
type: "POST",
data: {values:my_values},
success:function(response){
alert("success: " + response);
location.href = linkTo; //Redirect the user to the new page
},
error:function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
},
});
});
这篇关于jQuery锚点单击事件会执行ajax发布,重定向后会导致执行错误回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!