jQuery 在表单提交时将 Javascript 数组添加到 POST 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11227413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a Javascript array to POST variable on form submit
提问by Stephen305
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?
我有一个 Javascript 数组,我想在提交表单时将其添加到 post 数组中。除了已经从表单发布的其他变量之外,还应该添加 Javascript 数组。有没有办法在 JQuery 中做到这一点?
Ex.
前任。
Form:
形式:
<form id="my-form" action="/create.php" method="post">
<input id="first_name" type="text" />
<input id="last_name" type="text" />
</form>
Javascript array:
Javascript数组:
<script type="text/javascript">
var external_ids = [{"name":"SSN","value":"555-55-5555"},
{"name":"PID","value":"GBNT22"}];
</script>
This is what I would like the resulting PHP $_POST array to look like, if possible:
如果可能,这就是我希望生成的 PHP $_POST 数组的样子:
Array
(
[first_name] => John
[last_name] => Smith
[external_ids]=>
(
[SSN] => 555-55-5555
[PID] => GBNT22
)
)
采纳答案by Marc
There you go:
你去吧:
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);?
Find the code in this jsfiddleas well.
也可以在这个jsfiddle 中找到代码。
回答by Stefano Ortisi
There is the serialize() function on jQuery. Had you check this?
jQuery 上有 serialize() 函数。你检查过这个吗?
Or you can use something like this:
或者你可以使用这样的东西:
function onSubmit(){
var toSend = [
first_name : 'John',
last_name : 'Smith',
external_ids : {
SSN: '555-55-5555',
PID: 'GBNT22'
}
];
$.post( yourUrl, toSend, function(data){
//callback
} );
}
}