简体   繁体   English

jQuery.ajax:如何获取易于发送的数据?

[英]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进行。

    $.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. 我希望能够拦截这些POST,而通过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. 因此,问题是:如何选择将要传递的所有数据,将其转换为查询字符串,然后将其插入data: ???,部分。

Thanks 谢谢

You need to intercept the submit event. 您需要拦截submit事件。 Bind an event handler on your <form> elements. <form>元素上绑定事件处理程序。 When encountered, stop its propagation and its default behavior by returning false from within that event handler. 遇到这种情况时,可通过从该事件处理程序中返回false来停止其传播及其默认行为。

Now, you can create your .ajax() request in that handler to. 现在,您可以在该处理程序中创建您的.ajax()请求。 To create a serialized form of your form-data into a query-string, use jQuerys .serialize() method on that form aswell. 要将表单数据的序列化表单创建为查询字符串,请在该表单上也使用jQuerys .serialize()方法。

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/ http://api.jquery.com/serialize/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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