代码之家  ›  专栏  ›  技术社区  ›  Jay Corbett

使用jQuery 1.4在ajax调用中传递数组

  •  10
  • Jay Corbett  · 技术社区  · 16 年前

    以下代码适用于我使用jQuery1.2.6的情况,但在1.4中会导致代理错误。

    var items = new Array();
    items[0] = "Item 1";
    items[1] = "Item 2";
    items[2] = "Item 3";
    
    var dataToSend = {'_service' : myService, '_program' : myProgram, 'selections' : items} ;
    
    $.ajax({    
     type: "post",
     url: myURL,
     dataType: "text",
     data: dataToSend,
     success: function(request) {$('#results').html(request); } // End success
    }); // End ajax method
    

    错误: (字段名“selections[]”中的字符“[”无效。字段名称中不允许使用此字符。)

    jQuery在ajax调用中处理数组的方式有变化吗?或者这是传递数组的错误方式?

    编辑:@jvenema的答案解决了我的问题。使用“传统”设置,可以使jQuery像以前的版本一样处理参数。这里有一些关于这一变化的附加链接 jQuery.ajax() , jQuery.param() 还有一篇博文 jQuery 1.4 $.param demystified .

    要么是一般性声明

    jQuery.ajaxSettings.traditional = true;
    

    或者作为ajax调用中的附加选项

    $.ajax({    
     traditional: true,
     type: "post",
     url: myURL,
     dataType: "text",
     data: dataToSend,
     success: function(request) {
       $('#results').html(request);
     }  // End success
    }); // End ajax method
    
    2 回复  |  直到 16 年前
        1
  •  21
  •   Jerod Venema    16 年前

    jQuery1.4更新为使用PHP语法发送数组。您可以使用以下命令将其切换为旧样式:

    jQuery.ajaxSetting.traditional = true;
    

    看见 here 详情请参阅。

        2
  •  0
  •   Community Mohan Dere    9 年前

    'selections' : {items : ['Item 1', 'Item 2', 'Item 3']}
    

    我认为这也会起作用。

    'selections' : {items : items}
    

    看一看 here