Intercept form POST string and send via AJAX inste

2019-01-23 16:02发布

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 get the POST string from. I could reproduce the string from the form's inputs, but this seems dubious.

3条回答
够拽才男人
2楼-- · 2019-01-23 16:35

use .serialize(), it will ncode a set of form elements as a string for submission.

$('form').serialize() 
查看更多
smile是对你的礼貌
3楼-- · 2019-01-23 16:40
// 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.

查看更多
你好瞎i
4楼-- · 2019-01-23 16:42

You can do of course - you prevent your form from submitting as usual, you take its data and perform a POST via jQuery:

$(form).submit(function(event){

    // prevents default behaviour, i.e. reloading the page
    event.preventDefault();

    $.post(

        $(this).attr('action'), // the form's action
        $(this).serializeArray(),   // the form data serialized
        function(data)
        {

            // what you are supposed to do with POST response from server

        }

    )

});
查看更多
登录 后发表回答