jQuery输入具有相同的名称和方括号 [英] jQuery input with same name and square brackets
问题描述
我有一个使用jQuery和Ajax发布表单数据的表单,但不能让它发送具有相同名称和方括号的输入值。
I have a form that is using jQuery and Ajax to post the form data, but cannot get it to send the values of inputs with the same name and square brackets.
输入看起来像这样,并且会有不同的值:
The inputs look like this and will have different values:
<input type="text" name="service[]" value="Value 1">
以下是获取值的变量:
var service = $("input[name=service\\[\\]]")
然后收集通过Ajax发送的数据的var如下所示:
Then the var for collecting the data to send via Ajax looks like this:
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&service=' + service.val() + '&brief=' + encodeURIComponent(brief.val());
然后在用于发送邮件的PHP脚本中包含以下内容...
Then in the PHP script for sending the mail includes the following...
$service = $_POST['service'];
$body .= implode(' | ', $service);
所以我的问题是,如何获取名称<$ c $的输入值c> name = service [] 并通过Ajax发送。
So my question is, how do I get the values of the inputs with the name name=service[]
and send them via Ajax.
提前致谢:)
推荐答案
不是你问题的确切答案,但有一种更简单的方法可以做到这一点。
Not an exact answer to your question, but there is an easier way to do this.
包裹你的表单中的输入字段并生成 on-submit
-event。返回此事件为false,因此实际上并未提交。
Wrap your input-fields in a form and make an on-submit
-event. Return this event false so it's not actually submitted.
这就是诀窍。在将事件返回false之前,请执行ajax-request。给表单一个id并使用seralize-method创建一个json-string。
Here's the trick. Before you return the event false, do the ajax-request. Give the form an id and use the seralize-method to make a json-string.
[...]
data: $('#formIDGoesHere').serialize(),
[...]
如果您将此文件作为POST变量发布到PHP文件中,则所有值都不可用,就像它们通常位于 $ _ POST
中一样。
If you post this to your PHP file as POST-variables, all your values are not available like they normally would be in $_POST
.
这篇关于jQuery输入具有相同的名称和方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!