将 JavaScript 数组作为 JSON 值发送?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2814625/
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
Send a JavaScript array as a JSON value?
提问by thedp
How can I send a JavaScript array as a JSON variable in my AJAX request?
如何在我的 AJAX 请求中将 JavaScript 数组作为 JSON 变量发送?
回答by Sean Kinsey
This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.
这需要您将 javascript 数组序列化为字符串,这可以使用 JSON 对象轻松完成。
var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
data:{
param: myJson
}
});
As the JSON object is not present in older browsers you should include Douglas Crockfords json2library
由于旧浏览器中不存在 JSON 对象,因此您应该包含 Douglas Crockfords json2库
If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode
如果您已经依赖一些包含编码/序列化方法的库,那么您可以改用它。例如 ExtJs 有Ext.encode
回答by timdev
If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org
如果您没有使用可以为您执行此操作的 javascript 库(jQuery、prototype.js 等),您始终可以使用json.org 中的示例代码
回答by Cristian
Just encode the array and send it as part of your AJAX recuest:
只需对数组进行编码并将其作为 AJAX recuest 的一部分发送:
http://www.openjs.com/scripts/data/json_encode.php
http://www.openjs.com/scripts/data/json_encode.php
There are too many others encoders, or even plugins for JQuery and Mootools :D
有太多其他编码器,甚至是 JQuery 和 Mootools 的插件:D
回答by Sarvar Nishonboev
Here's an example:
下面是一个例子:
var arr = [1, 2, 3];
$.ajax({
url: "get.php",
type: "POST",
data: {ids:arr},
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
In get.php:
在 get.php 中:
echo json_encode($_POST['ids']);
Array will be converted to object using {ids:arr}, pass the object itself and letting jQuery do the query string formatting.
数组将使用 {ids:arr} 转换为对象,传递对象本身并让 jQuery 进行查询字符串格式化。

