后阵的jQuery连载 [英] post array jquery serialize
问题描述
我想发布一个javascript数组到PHP页面。阵列必须是关联的。我的结构是这样的:
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" />
当我创建数组是:
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,
});
问题是,在萤火,如果我看的设置,它是空的职位。我需要通过这样的,因为我会每个这些设置考虑到PHP和序列化并将其插入到一个字段在数据库中的阵列。这样我可以拉设置恢复出来,反序列化重新填充这些字段。任何想法我怎么可以这样?
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?
推荐答案
我推荐两个改变。
首先,由于要在PHP关联数组,你应该使用一个对象,而不是在Javascript数组:
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)
}
});
的重要部分是$ .PARAM以来该对象转换成一系列的参数(适合于QUERY_STRING)
The important part is the $.param since that converts the object into a series of parameters (suitable for a query_string).
你需要得到它的工作在服务器上做的最后一件事是分析它在PHP中:
The final thing you need to do on the server to get it working is parse it in PHP:
parse_str($_POST['settings'], $settings);
现在,你可以在 $设置访问一切
变量就像你在JavaScript中能。
Now you can access everything in the $settings
variable just like you could in JavaScript.
$settings['id'] = "value";
这篇关于后阵的jQuery连载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!