jQuery: Capture anchor href onclick and submit asynchronously

后端 未结 3 384
清歌不尽
清歌不尽 2020-12-23 21:09

I almost never get to play with client-side stuff, and this presumably simple task is kicking my butt :)

I have some links. OnClick I want to prevent the default act

相关标签:
3条回答
  • 2020-12-23 21:23

    The problem here is that the Events are not being attached to your element because they are not being bound in DOM ready event . Try including your events in DOM ready event and if it works you will see the alert

    <script> 
        $(function() {
             $('a').click(function(event) {
                event.preventDefault();
                alert('fff')
            //here you can also do all sort of things 
            });
        }); 
    </script>
    

    After this send the Ajax request and submit the form in the Success callback function..

    <script> 
        $(function() {
             $('a').click(function(event) {
                 event.preventDefault();
                 $.ajax({
                     url: 'url',
                     dataType :'json',
                     data : '{}',
                     success :  function(data){
                         // Your Code here
    
                         $('#form').submit();
                     }
                 })
            });
        }); 
    </script>
    
    0 讨论(0)
  • 2020-12-23 21:24
    $('a').click(function(event) { 
        event.preventDefault(); 
        $.ajax({
            url: $(this).attr('href'),
            success: function(response) {
                alert(response);
            }
        });
        return false; // for good measure
    });
    
    0 讨论(0)
  • 2020-12-23 21:41

    Try this

    $('a').click(function (event) 
    { 
       event.preventDefault(); 
    
       var url = $(this).attr('href');
       $.get(url, function(data) {
         alert(data);
        });
    
     });
    
    0 讨论(0)
提交回复
热议问题