将3d数组格式化为GET或POST请求

时间:2017-01-10 15:26:21

标签: javascript arrays post get

我有一个JavaScript 3D数组(存储在标准数组中的关联数组)。在AJAX函数的GET或POST请求字符串中表示这个的正确方法是什么?

var arr = [];

var assocArr1 = {};
var assocArr1["name"] = "first name";
var assocArr1["type"] = "first type";
arr.push(assocArr1);

var assocArr2 = {};
var assocArr2["name"] = "second name";
var assocArr2["type"] = "second type";
arr.push(assocArr2);

1 个答案:

答案 0 :(得分:1)

如果你使用上面的arr对象在后端使用php,那么这里有一种方法:

var str_json = JSON.stringify(arr);  //gives me the JSON string.

request= new XMLHttpRequest();

request.open("POST", "JSON_Handler.php", true);

request.setRequestHeader("Content-type", "application/json");

request.send(str_json);

对于jquery.post,你可以这样做:

var str_json = JSON.stringify(arr); // gives me the JSON string.

$.ajax({
  type: "POST",
  url: url,
  data: str_json,
  success: success,
  dataType: "json"
 });