使用 jQuery.ajax post 函数将 javascript 数组中的数据传递给服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8631748/
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 data in javascript array to server with jQuery.ajax post function?
提问by Rowan
I was wondering if its possible to pass data stored in a javascript array to the server using jQuery's ajax function..
我想知道是否可以使用 jQuery 的 ajax 函数将存储在 javascript 数组中的数据传递到服务器。
In the jQuery documentation it specifies:
在 jQuery 文档中,它指定:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
can "data" be set to an array? How would this work given it seems data is expecting key value pairs? I currently just hard code the values but I want it to be a more dynamic approach..my current code is:
“数据”可以设置为数组吗?鉴于数据似乎需要键值对,这将如何工作?我目前只是对值进行硬编码,但我希望它是一种更动态的方法..我当前的代码是:
jQuery.ajax({
url: "/createtrips/updateitin",
type: 'POST',
data: {place1: 'Sydney', place2: 'London'},
dataType: 'json',
});
回答by Rowan
I created an array like this:
我创建了一个这样的数组:
var placesfortrip = {};
then added to it like this:
然后像这样添加到它:
placesfortrip["item"+counter] = inputVal;
(where counter
is an incremented counter variable)
then assigned this to the data
property of the ajax call
(其中counter
是一个递增的计数器变量)然后将其分配给data
ajax 调用的属性
jQuery.ajax({
url: "/createtrips/updateitin",
type: 'POST',
data: placesfortrip,
dataType: 'json',
});
and if I look at the XHR tab in firebug it appears those values get posted!
如果我查看 firebug 中的 XHR 选项卡,似乎这些值已发布!
回答by kevinji
Yes, jQuery.ajax()
supports the passing of arrays. It simply serializes the array into a name-value string.
是的,jQuery.ajax()
支持数组的传递。它只是将数组序列化为名称-值字符串。
If value is an Array, jQuery serializes multiple values with same key based on the value of the
traditional
setting (described below).
如果 value 是一个数组,jQuery 会根据
traditional
设置的值(如下所述)使用相同的键序列化多个值。
回答by Travis J
I believe you would like to look into using JSON to pass those values.
我相信您想研究使用 JSON 来传递这些值。
回答by Derk Arts
Check out jQuery serialize: http://api.jquery.com/serialize/
查看 jQuery 序列化:http: //api.jquery.com/serialize/
$('form').submit(function() {
alert($(this).serialize());
return false;
});
This produces a standard-looking query string:
a=1&b=2&c=3&d=4&e=5