I am trying to post a javascript array to a php page. The array has to be associative. My structure looks like this:
<input id="test" value="1" class="settings" />
<input id="test1" value="2" class="settings" />
When I create the array it is:
var myArray = new Array();
$(".setttings").each(function(){
myArray[$(this).attr("id")] = $(this).val();
});
Now when I post that data I am just doing:
$.ajax({
type: "POST",
url: 'post.php",
data: "settings="+myArray,
});
The problem is that in firebug if I look at the post for settings it is empty. I need the array passed like this because I am going to take each of those settings into php and serialize them and insert them into a field in a database. That way I can pull the settings back out and unserialize to repopulate those fields. Any ideas how I can开发者_如何转开发 do this?
I would recommend two changes.
First, since you want an associative array in PHP, you should use an Object, not an Array in Javascript:
var myObject = new Object();
$(".setttings").each(function(){
myObject[$(this).attr("id")] = $(this).val();
});
Next, you want to pass it to the data section a little differently:
$.ajax({
type: "POST",
url: "post.php",
data: {
settings: $.param(myObject)
}
});
The important part is the $.param since that converts the object into a series of parameters (suitable for a query_string).
The final thing you need to do on the server to get it working is parse it in PHP:
parse_str($_POST['settings'], $settings);
Now you can access everything in the $settings
variable just like you could in JavaScript.
$settings['id'] = "value";
Just a small update to Dougs answer.
data: {
settings: $.param(myObject)
}
can be changed to
data: myObject
The jQuery ajax function will automatically turn your object into a string.
精彩评论