I’m trying to pass an array to jquery’s .ajax() function’s data parameter. The first approach is that I made my 2-dimensional array like this:
var arr = new Array();
for(i in someArray){
arr[i] = new Array();
arr[i].lon = "x";
arr[i].lat = "y";
}
Then I try to pass this as data in $.ajax():
$.ajax({
data: { vals : arr },
async: false,
type: "POST",
url: "namedb.php",
dataType: "script",
success: function(data){
result = data;
alert(result);
}
});
test.php just returns all the values of $_POST. So alert() here returns:
Array
(
)
But if I changed the code to:
var arr = new Array();
for(i in someArray){
arr[i] = new Array();
arr[i] = { lon: "x", lat: "y" };
}
the alert() returns what I expected:
Array
(
[vals] => Array
(
[0] => Array
(
[lat] => "y",
[lon] => "x"
)
...
)
)
I know that both methods initializes the variables/attributes of each element of arr (or am I wrong?). But why do the 2 approach behaves differently? (Sorry I could’ve shorten my question, but I guess I need to explain how I found it).
EDIT: I had added the initialization (arr[i] = new Array();). I must have erased it during the editing of the question. But still the same problem.
That is because you did not initialize the array elements.
Actually, I prefer to write
Because I don’t have to type
arr[i]3 times.Using
for inloops over an array is wrong, you should useforloops or jQuery’s$.eachOr
Using
Array.prototype.pushfor adding things to an array is easier, because you don’t need to know the next index of an array, also compare witharr[arr.length]=something.And now what you’re doing is collect data from an array and translate it into another array. jQuery already has a function that does this:
$.map.Note that when using
$.each, the arguments arei, value, when you use$.map, they are switched.