开发者

passing a array to php via ajax?

开发者 https://www.devze.com 2023-03-04 21:04 出处:网络
I have this array var car = new Array(); car[\'brand\'] = \"Ford开发者_JS百科\"; car[\'color\'] = \"red\";

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 use Object instead of Array in these cases because the features that you want are actually features of Object and not of Array. Array just happens to extend Object (like any other object in JS and therefore you might as well have used Date, RegExp or String).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号