简体   繁体   中英

javascript convert array to object for send data by ajax

I would like to send a list of data by ajax. So I push all data in a 2d array

But the ajax of jquery not accept the array data, the data must be object or query string

since the Object of javascript is no push function, I must use array to build the list of data. Is there any function in jquery or javascript, let me

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.


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. 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"] .

You need to convert the object to a JSON string using JSON.stringify() .

http://json.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM