passing a array to php via ajax?
I have this array
var car = new Array();
car['brand'] = "Ford开发者_JS百科";
car['color'] = "red";
car['type'] = 1;
now, i tried sending this but php only tells me car is a undefined index:
$.post('regCar.php', { "car[]": car }, function(data) {
// some other lol here ...
});
Sending in "car[]": ["Ford", "red", 1]
works fine :( How can i pass in an associative array to php?
As mentioned in my comment, you should not use arrays this way. Only use arrays for numerical indexes:
Associative
Arrays
are not allowed... or more precisely you are not allowed to use non number indexes for arrays. If you need a map/hash useObject
instead ofArray
in these cases because the features that you want are actually features ofObject
and not ofArray
.Array
just happens to extendObject
(like any other object in JS and therefore you might as well have usedDate
,RegExp
orString
).
This is exactly the reason why the code does not work.
Have a look at this fiddle: The alert is empty meaning that jQuery is not serializing (and therefore sending) any data at all.
One might expect that it would at least send an empty value, like car[]=
but apparently it does not.
If you use an object:
var car = {};
it works
Read json_encode and json_decode
$.post('regCar.php', {'car': car}, function(data) { // - I changed the key value name });
You don't need to add the brackets in the data parameter
However, I recommend you use JS objects.
var car = {};
car.brand = "Ford";
car.color = "red";
car.type = 1;
If you're getting an undefined error on the PHP side, you'll need to post your PHP code.
EDIT
As @Felix Kling points out, dropping array in favor of objects will work for you.
精彩评论