javascript - 每个ajax请求发送一个数组

标签 javascript arrays ajax

我想以 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/

相关文章:

javascript - 即使使用 trackBy,Angular 2 也会在 ngFor 中重建 DOM

javascript - PhoneGap Ajax 调用

c - 警告 : assignment from incompatible pointer type by 2d pointers in the struct

javascript - 我如何才能确信用户没有更改文本框值?

ajax - Grails,在 AJAX 调用中处理 session 超时

javascript - HTML 5 图片调整大小

javascript - 在node.js中使用全局变量

Java XML 到数组

c - 从 C 文件中读取 2 个不同的列并将它们存储在 2 个不同的数组中?

javascript - setInterval 使异步 ajax 函数停止工作