【问题标题】:Jquery bind to link, execute some post jquery then load linkJquery绑定到链接,执行一些post jquery然后加载链接
【发布时间】:2023-03-25 23:33:01
【问题描述】:

有没有一种干净的方法可以在链接上绑定 jquery 帖子,并在帖子执行后加载链接,因为它应该正常执行?

这是我的代码:

$("a").bind('click', function(e){
     // disable click while we make a post request
     e.preventDefault();

     // make post request
     $.post('/blablabla/', { "datas" : mydatas } );
});

现在我禁用单击以允许我的脚本进行 POST,但我希望在我的 POST 被调用并成功执行后将链接带到目标页面。我想我需要一个回调,但找不到实现它的好方法。

提前致谢,

【问题讨论】:

    标签: jquery post callback


    【解决方案1】:

    为您的.post 调用添加一个成功函数,它将window.location 更改为点击链接的href

    $( 'a' ).bind( 'click', function( e )
    {
        var url;
    
        # disable click while we make a post request
        e.preventDefault();
    
        # get the url from the href attr
        url =  = $( this ).attr( 'href' );
    
        # make post request
        $.post(
            '/blablabla/',
            {
                datas: mydatas
            },
            function()
            {
                # send browser to url
                window.location = url;
            }
        );
    } );
    

    如果您希望即使 POST 失败也能进行重定向,您可以切换到使用 .ajax() 并使用 complete 选项:

    $( 'a' ).bind( 'click', function( e )
    {
        var url;
    
        # disable click while we make a post request
        e.preventDefault();
    
        # get the url from the href attr
        url =  = $( this ).attr( 'href' );
    
        # make post request
        $.ajax( {
            url: '/blablabla/',
            type: 'POST',
            data: {
                datas: mydatas
            },
            complete: function()
            {
                # send browser to url
                window.location = url;
            }
        );
    } );
    

    【讨论】:

      【解决方案2】:
      $("a").bind('click', function(e){
          # disable click while we make a post request
          e.preventDefault();
      
          # Save the link url
          var url = $(this).attr('href');
      
          # make post request
          $.post('/blablabla/', { "datas" : mydatas }, function() {
              # Post successful
              document.location(url);
          } );
      });
      

      您应该以某种方式防止“双击”。

      【讨论】:

        【解决方案3】:

        $.post 返回后,您可以重定向到 url 的 href。

        $("a").bind('click', function(e){
        
                # disable click while we make a post request
                e.preventDefault();
                var url = $(this).attr('href');
        
                # make post request
                $.post('/blablabla/', { "datas" : mydatas }, function(){
                     window.location = url;
                });
        
        });
        

        【讨论】:

          猜你喜欢
          • 2016-05-29
          • 1970-01-01
          • 2011-09-11
          • 2017-07-05
          • 2014-01-21
          • 1970-01-01
          • 2011-06-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多