我想以 ajax 请求的形式发送,其中数组(可以是任意长度)作为 1 个参数,如下所示:
mandatoryFields = [];
for (i = 1; i <= post_type_max_elements; i++) {
...
var mandatoryItem = []
mandatoryItem['optionName'] = optionName;
mandatoryItem['optionValue'] = optionValue;
}
var data = {
action: 'update_mandatory_fields',
post_type: select_post_type,
mandatoryFields: mandatoryFields
};
jQuery.ajax({
type: 'POST',
dataType: "json",
data: data,
...
似乎这不起作用,因为服务器参数 CommandFields 未定义。 哪种方法最好?
谢谢!
最佳答案
您可以使用 JSON.stringify()
将数组转换为字符串。
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
在您的示例中:
$.ajax({
type: "POST",
url: url,
data: {yourData: JSON.stringify(data)},
success: function(response){
//Callback function - do something if the request succeeded
}
});
请注意,您还可以使用 $.post()
而不是 $.ajax()
。
要使用 php
重建数组,您可以使用 json_decode($_POST['yourData']);
关于javascript - 每个ajax请求发送一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117413/