HTML Anchor tag redirect link after ajax request

后端 未结 3 955
独厮守ぢ
独厮守ぢ 2020-12-03 19:23

I\'m trying to write a method to catch user clicks on a site menu, but I want the process to be silent for the user, mainly, that when a user hovers over an anchor tag, it w

相关标签:
3条回答
  • 2020-12-03 20:11

    Use event.preventDefault, then on success, use location.href = self.href

    $(".selectAnchor, .menuAnchor").click(function(event){
        event.preventDefault();
        console.log(event.target.nodeName);
        var self = this;
    
        $.ajax({
          type: 'POST',
          url: 'http://localsite/menuRedirect.php',
          data: {id:0, module:'Module',source:'Source'},
          complete: function(data){
            console.log("DONE");
            location.href = self.href;
          }
        });
    });
    

    Or make use of the context property to remove var self = this

    $(".selectAnchor, .menuAnchor").click(function(event){
        event.preventDefault();
        console.log(event.target.nodeName);
    
        $.ajax({
          type: 'POST',
          context: this,
          url: 'http://localsite/menuRedirect.php',
          data: {id:0, module:'Module',source:'Source'},
          complete: function(data){
            console.log("DONE");
            location.href = this.href;
          }
        });
    });
    
    0 讨论(0)
  • 2020-12-03 20:17

    Latest chrome browser wont complete the ajax request. Since the browser page got new url request from the user, so browser will kill the thread immediately.

    98% of times you can see that the ajax request got cancelled in a network tab.

    So the solution is use sendBeacon API. This will perform a POST request asynchronously. Google analytics uses this code to perform the event trackings (Ex: click).
    https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

     navigator.sendBeacon("{{url}}", param);
    
    0 讨论(0)
  • 2020-12-03 20:22

    Try This

    <div class="selectNode" id="selectNode_1" style="color: rgb(229, 229, 229); background-color: rgb(47, 47, 47); ">
      <a href="#" class="selectAnchor" style="color: rgb(229, 229, 229); ">
        Google
      </a>
      <img class="childImage" src="icon.png">
    </div>
    

    Then this in jquery:

    $(".selectAnchor, .menuAnchor").click(function(event){
        event.preventDefault();
        console.log(event.target.nodeName);
        //event.preventDefault();
    
        $.ajax({
          type: 'POST',
          url: 'http://localsite/menuRedirect.php',
          data: {id:0, module:'Module',source:'Source'},
          complete: function(data){
            console.log("DONE");
            window.location = "http://www.google.com"
          }
        });
    });
    
    0 讨论(0)
提交回复
热议问题