使用 jQuery 1.4 在 ajax 调用中传递数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2195471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing arrays in ajax call using jQuery 1.4
提问by Jay Corbett
The following code works for me using jQuery 1.2.6 but causes a broker error in 1.4.
以下代码适用于我使用 jQuery 1.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
The broker error I get indicates that what is being passed in selections is 'selections[]'
我得到的经纪人错误表明选择中传递的是“选择[]”
ERROR:(Invalid character "[" in field name "selections[]". This character is not allowed in field names.)
错误:(字段名称“selections[]”中的无效字符“[”。字段名称中不允许使用此字符。)
Was there a change in how jQuery handles arrays in an ajax call? or was this an incorrect way to pass an array?
jQuery 在 ajax 调用中处理数组的方式有变化吗?或者这是传递数组的不正确方法?
Any help would be appreciated.
任何帮助,将不胜感激。
EDIT: The answer from @jvenema solved my problem. With the "traditional" setting you can cause jQuery to handle the parameters like the previous version. Here are some additional links which talk about the change jQuery.ajax(), jQuery.param()and a blog post jQuery 1.4 $.param demystified.
编辑:@jvenema 的回答解决了我的问题。使用“传统”设置,您可以使 jQuery 像以前的版本一样处理参数。这里有一些附加链接,它们讨论了jQuery.ajax()、jQuery.param()和博客文章jQuery 1.4 $.param demystified 的变化。
Either a general statement of
要么是一般性声明
jQuery.ajaxSettings.traditional = true;
or as an additional option in the ajax call
或作为 ajax 调用中的附加选项
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend,
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
回答by jvenema
回答by Fitzchak Yitzchaki
You can specify the array as Json array.
您可以将数组指定为 Json 数组。
'selections' : {items : ['Item 1', 'Item 2', 'Item 3']}
'selections' : {items : ['Item 1', 'Item 2', 'Item 3']}
I think that this will work too.
我认为这也会奏效。
'selections' : {items : items}
'selections' : {items : items}
Take a look herefor addition resource.
看看这里的附加资源。