在表单提交时将Javascript数组添加到POST变量 [英] Add a Javascript array to POST variable on form submit
本文介绍了在表单提交时将Javascript数组添加到POST变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Javascript数组,我想在提交表单时将其添加到post数组中.除了已经从表单中发布的其他变量之外,还应该添加Javascript数组.有没有办法在JQuery中做到这一点?
I have a Javascript array that I would like to add to the post array when a form is submitted. The Javascript array should be added in addition to other variables already being posted from the form. Is there a way to do this in JQuery?
例如.
表格:
<form id="my-form" action="/create.php" method="post">
<input id="first_name" type="text" />
<input id="last_name" type="text" />
</form>
JavaScript数组:
Javascript array:
<script type="text/javascript">
var external_ids = [{"name":"SSN","value":"555-55-5555"},
{"name":"PID","value":"GBNT22"}];
</script>
如果可能的话,我希望得到的PHP $ _POST数组看起来像这样:
This is what I would like the resulting PHP $_POST array to look like, if possible:
Array
(
[first_name] => John
[last_name] => Smith
[external_ids]=>
(
[SSN] => 555-55-5555
[PID] => GBNT22
)
)
推荐答案
去那里:
var external_ids = [{"name": "SSN", "value": "555-55-5555"},
{"name": "PID", "value": "GBNT22"}];
// form fields
var values = {};
var fields = $('#myForm :input');
$.each(fields, function(i, field) {
var dom = $(field),
name = dom.attr('id'),
value = dom.val();
values[name] = value;
});
// add array
values.external_ids = {};
$.each(external_ids, function(i, field) {
values.external_ids[field.name] = field.value;
});
// post data
$.post('/endpoint', values);
也在此 jsfiddle 中查找代码.
这篇关于在表单提交时将Javascript数组添加到POST变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文