[英]javascript convert array to object for send data by ajax
I would like to send a list of data by ajax. 我想通过ajax发送数据列表。 So I push all data in a 2d array 所以我将所有数据推送到2d数组中
But the ajax of jquery not accept the array data, the data must be object or query string 但是jquery的ajax不接受数组数据,数据必须是对象或查询字符串
since the Object of javascript is no push function, I must use array to build the list of data. 由于javascript的Object没有push函数,我必须使用array来构建数据列表。 Is there any function in jquery or javascript, let me 在jquery或javascript中是否有任何功能,让我
var countLine=$("line").length;
var lines=$("line");
var lineArr=new Array();
var linesArr=new Array();
var x1, y1, x2, y2;
for(i=0; i<countLine; i++)
{
lineArr['x1']=lines[i].getAttributeNS(null, "x1");
lineArr['y1']=lines[i].getAttributeNS(null, "y1");
lineArr['x2']=lines[i].getAttributeNS(null, "x2");
lineArr['y2']=lines[i].getAttributeNS(null, "y2");
linesArr.push(lineArr);
}
$.ajax({
type: "POST",
url: "test.php",
data: linesArr,
async: true,
cache: false,
success: function(data){
$("#txt").text(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("fail");
}
});
Change 更改
data: linesArr
to 至
data: { linesArr: linesArr }
This will send an object with a single property, "linesArr"
, which contains the value of your array. 这将发送一个具有单个属性"linesArr"
的对象,该属性包含数组的值。
EDIT: you have a bigger problem. 编辑:你有一个更大的问题。 You are trying to store non-numeric properties in an array, as shown in this line: 您正尝试在数组中存储非数字属性,如下所示:
lineArr['x1']=lines[i].getAttributeNS(null, "x1");
You are also reusing the same lineArr
"array" each time through the loop. 每次循环时,您也重复使用相同的lineArr
“数组”。 The following code would work much better: 以下代码可以更好地工作:
var lines = $("line");
var linesArray = [];
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
linesArray.push({
x1: line.getAttributeNS(null, "x1"),
y1: line.getAttributeNS(null, "y1"),
x2: line.getAttributeNS(null, "x2"),
y2: line.getAttributeNS(null, "y2")
});
}
Then you would access your data like $_POST["linesArr"][0]["x1"]
. 然后你将访问你的数据,如$_POST["linesArr"][0]["x1"]
。
You need to convert the object to a JSON string using JSON.stringify()
. 您需要使用JSON.stringify()
将对象转换为JSON字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.