使用额外 id 提交的 jQuery 表单序列化

2024-02-18

我有一个这样的表格:

 <form id="cform">
    <label>folder name:</label>
    <input type="text" name="Folder[name]" />
    <input id="cfolder" type="submit" value="create" />
 </form>

我想在 jQuery ajax 中提交表单,所以我有这样的代码:

 $.ajax({
    type: "POST",
    url: "/folder/create",
    data: $('#cform').serialize(),
    success: function(msg){
        //sucess
    }
  });

到目前为止这一切都很容易,但现在我想提交一个额外的动态 id($id 值可用)以及整个表单。我怎样才能做到这一点?我试过这个:

 data: $('#cform').serialize()+"&Folder[id]="+$id,

但没有成功,服务器端没有获取到id。对我来说最棘手的部分是文件夹[名称],文件夹[id], 因为服务器端接收php中的数据是这样的:

if(isset($_POST['Folder'])){
    //assign data here
}

希望这是清楚的,感谢您的任何建议。


作为替代建议:

You can use .serializeArray [docs] http://api.jquery.com/serializeArray/ and $.param [docs] http://api.jquery.com/jQuery.param/. Then jQuery will take care of all the encoding:

var data = $('#cform').serializeArray();
data.push({name: "Folder[id]", value: $id});

// later

data: $.param(data);

我不明白你是否有问题$_POST['Folder']或不,但如果您使用末尾带有括号的名称,PHP 会将数据解析为数组。

因此您可以使用以下方式访问数据$_POST['Folder']['name'] and $_POST['Folder']['id'].

欲了解更多信息,请查看来自外部源的变量 http://php.net/manual/en/language.variables.external.php.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用额外 id 提交的 jQuery 表单序列化 的相关文章

随机推荐