Intercept form POST string and send via AJAX instead

后端 未结 3 1017
名媛妹妹
名媛妹妹 2020-12-16 00:12

Is it possible to intercept a form\'s POST string and send it via AJAX instead? I could use $(\'form\').submit() to intercept the POST event, but I don\'t see where I can ge

3条回答
  •  生来不讨喜
    2020-12-16 00:48

    // capture submit
    $('form').submit(function() {
         var $theForm = $(this);
    
         // send xhr request
         $.ajax({
             type: $theForm.attr('method'),
             url: $theForm.attr('action'),
             data: $theForm.serialize(),
             success: function(data) {
                 console.log('Yay! Form sent.');
             }
         });
    
         // prevent submitting again
         return false;
    });
    

    Note that as Phil stated in his comment that .serialize() doesn't include the submit button. If you also need to value of the submit buton you would have to add it manually.

提交回复
热议问题