通过$ .ajax()发送表单元素和数组

时间:2016-06-17 11:41:16

标签: javascript java jquery ajax

我需要通过$ .ajax()方法传递一些表单元素和数组。如何通过ajax发送序列化和数组?

我的代码如下:

function loadgraficosajax(){
		var arr = ['331234','142323','327767'];
  
    	var data = $('#p-form').serialize;
  
        $.ajax({
            type: "POST",
            url: "/page/show",
            data: data,
            dataType : 'html',
            success: function (msg) {
                $(document).ajaxComplete(function (event, request, settings) {
                    $('.has-error').removeClass('has-error');

                    $(document).off('ajaxComplete').off('ajaxSend');
                    $('#addajax').html(msg);
                 });
            }
        });
	}

3 个答案:

答案 0 :(得分:1)

serialize是jQuery中的方法,而不是属性,因此您应该以这种方式调用它:

var data = $('#p-form').serialize();

要传递数组,您需要使用param方法并将数组修改为Object内部,其中数组名称为object属性:

var arr = { arr: ['331234','142323','327767'] };
var data = $('#p-form').serialize();
data += '&' + $.param( arr );

param会将您的对象转换为序列化字符串:

console.log($.param( arr )); // "arr[]=331234&arr[]=142323&arr[]=327767"

答案 1 :(得分:0)

 var formData = new FormData($('#p-form')[0]);

 var arr = ['331234','142323','327767'];

 // append array to formData
 formData.append('arr',JSON.stringify(arr));

 $.ajax({
     type: "POST",
     url: "/page/show",
     data: formData,
     success:.....

答案 2 :(得分:0)

您可以将两个项目捆绑在一个可以发送的字符串化对象中:

function loadgraficosajax(){
    var arr = ['331234','142323','327767'];

    var data = $('#p-form').serialize();

    var request = {
        array: arr,
        elements: data
    }

    var data = JSON.stringify(request);

    $.ajax({
        type: "POST",
        url: "/page/show",
        data: data,
        dataType : 'json',
        success: function (msg) {
            $(document).ajaxComplete(function (event, request, settings) {
                $('.has-error').removeClass('has-error');

                $(document).off('ajaxComplete').off('ajaxSend');
                $('#addajax').html(msg);
             });
        }
    });
}