简体   繁体   English

如何使用ajax将数组作为数据发送

[英]How can send array as an data using ajax

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post 请参阅附件jsfiddle链接,我需要从多种形式收集数据并将数据组合为单个数据数组,将其发送到服务器(spring mvc控制器)以使用ajax.post持久化

Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it. 请让我知道执行此操作的最佳方法,将我的数组通过ajax调用转换为Json还是必须对其做一些魔术。

Thanks http://jsfiddle.net/6jzwR/1/ 谢谢http://jsfiddle.net/6jzwR/1/

<form id="form1" name="formone" class="myclass">
    <input type="text" id="txt11" name="txt11" value="name1" />
    <input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
    <input type="text" id="txt21" name="txt21" value="name3" />
    <input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />

(function ($) {
    $(document).ready(function () {
        alert("serialize data :" + $('.myclass').length);
        var mydata = null;
        $('#button').on('click', function (e) {

            $('.myclass').each(function () {
                alert("serialize data :" + $(this).serialize());
                if ((mydata === null) || (mydata === undefined)) {
                    mydata = $(this).serializeArray();
                    alert("My data is null");
                } else {
                    mydata = $.merge(mydata, $(this).serializeArray());
                    alert("My data final data after merger " + test);
                }
            });

        });
    });
}(jQuery));

Try this: 尝试这个:

var array = $('input[type="text"]').map(function() {
    return $(this).val();
}).get();

alert(JSON.stringify(array));

Demo . 演示

You can put all the forms' data in an array and join them with & 您可以将所有表单的数据放入数组中,并使用&

var formdata = []
$('.myclass').each(function(){
    formdata.push($(this).serialize());
});
var data = formdata.join('&');

http://jsfiddle.net/6jzwR/3/ http://jsfiddle.net/6jzwR/3/

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

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