【问题标题】:store data via ajax and then go to that URL通过 ajax 存储数据,然后转到该 URL
【发布时间】:2016-06-10 12:20:49
【问题描述】:

我在这里寻求帮助。

<a class="text" href="http://test.com?id=87"><img src="/2016/02/BlueFantasyThumb.jpg"><h3>Milky</h3></a>

当我点击它时,我需要做一些我知道该怎么做的 ajax 事情。但问题是我需要执行 ajax 然后转到那个 href 链接。

点击后我知道使用 e.preventDefault();我们可以防止默认行为。但情况是我不想阻止这种情况。我想在该 ajax 实现之后发生该事件,而观众点没有任何障碍。

任何类型的输入都会对我有很大帮助。谢谢。

【问题讨论】:

标签: javascript php jquery ajax events


【解决方案1】:

您可以将href 值存储在变量中,调用e.preventDefault() 以防止重定向并运行您的ajax 代码。在您的 ajax 成功回调中,您可以选择 href 值并使用 javascript 重定向到该链接。

$("a.text").on("click", function(e){
 e.preventDefault();
 var href = $(this).attr("href");
 $.ajax({
  url: URL,
  data: DATA,
  success: function(response){
   // your code here to be executed before redirecting
   window.location.href = href;
  }//success
 });//ajax
});//click

【讨论】:

    【解决方案2】:

    1) 设置html喜欢

    <a class="text" data-href="http://test.com?id=87"><img src="/2016/02/BlueFantasyThumb.jpg"><h3>Milky</h3></a>
    

    2) 添加点击事件

    $(".text").click(function() { // set ajax
       var url = $(this).attr("data-href");
       $.ajax({
         url: "ajax.php", // set required url here
       }).done(function() {
         alert("sucess")
         window.location.href = url;  // redirect page in ajax success
       });
    });
    

    【讨论】:

      【解决方案3】:

      将href改为javascript:;

      然后你的ancor标签onclick事件调用ajax调用的函数

      ajax成功函数内部

      window.location.href = "http://test.com?id=87";

      【讨论】:

        猜你喜欢
        • 2020-04-21
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多