简体   繁体   中英

jQuery.ajax: How do I get the data to send easily?

I have lots of forms on a project I'm working on.

All the forms pretty much go through AJAX.

    $.ajax({
        type: "GET",
        cache: false,
        url: $(this).attr("action"),
        data: ???,
        success: function(msg){
        }
    });

I want to be able to intercept these POST's and instead run them through AJAX.

The code is written into a method that will be reused.

So the question is: How can I select all the data that was going to be passed, turn it into a query string and insert it into the data: ???, part.

Thanks

You need to intercept the submit event. Bind an event handler on your <form> elements. When encountered, stop its propagation and its default behavior by returning false from within that event handler.

Now, you can create your .ajax() request in that handler to. To create a serialized form of your form-data into a query-string, use jQuerys .serialize() method on that form aswell.

For instance:

$('#myFormId').on('submit', function( event ) {
    $.ajax({
        type: "GET",
        cache: false,
        url: $(this).attr("action"),
        data: $(this).serialize(),
        success: function(msg){
        }
    });

    return false;
});

Or just create that as delegated event, which handles all of your forms, like

$(document).on('submit', 'form', function( event ) {
});

Use serialize method:

http://api.jquery.com/serialize/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM