jQuery 将数组传递给 $.ajax() 中的 ajax 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8890524/
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
Pass array to ajax request in $.ajax()
提问by Poonam Bhatt
I want to send an array as an Ajax request:
我想发送一个数组作为 Ajax 请求:
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
How can I do this?
我怎样才能做到这一点?
回答by Diode
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
回答by FarligOpptreden
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
只需使用 JSON.stringify 方法并将其作为 $.ajax 函数的“数据”参数传递,如下所示:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
您只需要确保在页面中包含 JSON2.js 文件...
回答by BlackDivine
NOTE: Doesn't work on newer versions of jQuery.
注意:不适用于较新版本的 jQuery。
Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:
由于您使用的是 jQuery,请使用它的 seralize 函数来序列化数据,然后将其传递给 ajax 调用的数据参数:
info[0] = 'hi';
info[1] = 'hello';
var data_to_send = $.serialize(info);
$.ajax({
type: "POST",
url: "index.php",
data: data_to_send,
success: function(msg){
$('.answer').html(msg);
}
});