点击发送AJAX,但仍然转到href的URL


Send AJAX on click, but still go to URL of href

我正在尝试以下操作:

当用户单击链接时,我希望通过ajax更新数据库中特定表的特定列。但是我仍然希望用户被重定向到链接的href="<url>"

我在没有return false;的情况下尝试了jQuery,但ajax不起作用。

我尝试了return false;,但页面显然没有按照我的意愿重定向到url。

提前感谢您的帮助。

执行AJAX调用,完成后设置document.location
$('a').click(function(e){
    var href = this.href;  // get href from link
    e.preventDefault();  // don't follow the link
    $.ajax({
        url: '/path/to/site',
        data: {some: data},
        success: function(){
            document.location = href;  // redirect browser to link
        }
    });
});

您需要自己序列化这些操作。在事件处理程序中,首先运行AJAX请求,然后从标记中查找href,并使用位置重定向将客户端带到该URL。

将重定向代码放入成功回调:

$.ajax({
  ...
  success: function(){
    $(location).attr('href',url); // You URL inserted
  }
});