Php 使用Web Html表单创建Javascript数组
我有一张如下的表格 我需要使用JavaScript为每个单选按钮创建一个数组,并且需要使用Ajax发布到PHP脚本Php 使用Web Html表单创建Javascript数组,php,javascript,ajax,Php,Javascript,Ajax,我有一张如下的表格 我需要使用JavaScript为每个单选按钮创建一个数组,并且需要使用Ajax发布到PHP脚本 <form id="what" name="what" > <input type="radio" name="colors" id="red" value="red" />Red<br /> <input type="radio" name="colors" id="blue" value="blue" />Blue<br /
<form id="what" name="what" >
<input type="radio" name="colors" id="red" value="red" />Red<br />
<input type="radio" name="colors" id="blue" value="blue" />Blue<br />
<input type="radio" name="colors" id="green" value="green" />Green
<input type="radio" name="animals" id="dog" value="dog" />Red<br />
<input type="radio" name="animals" id="parrot" value="parrot" />Blue<br />
<input type="radio" name="animals" id="horse" value="horse" />Green
<button type="button" >send</button>
</form>
数据应按如下方式发送
radio[ { "radiobuttonename" => clicked value of the radio button},{ "radiobuttonename" => clicked value of the radio button}]
您可以使用以下代码(使用) HTML
<form id="what" name="what" >
<input type="radio" name="colors" id="red" value="red" />Red<br />
<input type="radio" name="colors" id="blue" value="blue" />Blue<br />
<input type="radio" name="colors" id="green" value="green" />Green<br /><br />
<input type="radio" name="animals" id="dog" value="dog" />Red<br />
<input type="radio" name="animals" id="parrot" value="parrot" />Blue<br />
<input type="radio" name="animals" id="horse" value="horse" />Green
<input type="submit" value="send" name="btn" />
</form>
您可以在php
中接收颜色
和动物
变量,如下所示
$color=$_POST['colors'];
$animal=$_POST['animals'];
这是一个框架,可以帮助您序列化此表单,并使用ajax将数据发送到某个端点
(function($) {
$('#what').bind('submit', function(e) {
$.post('/url/to/send', $(this).serialize(), function(response) {
console.log(response);
});
});
})(jQuery);
此代码用于用表单中的所有无线电值填充数组:
var theArray = []
$("#what > input[type='radio']").each(function(){
theArray.push($(this).val())
})
// theArray will be like this: red,blue,green,dog,parrot,horse
如果要将checked属性与数组一起传递,可以执行以下操作:
theArray.push($(this).val() + "@" + this.checked)
// theArray will be like this: red@false,blue@false,green@false,dog@true,parrot@false,horse@false
最后,将数组转换为字符串:
theArray = theArray.join("##")
现在您可以使用ajax发送数组了,只需使用jquery函数,如下所示
$('#what').on('submit', function(e) {
e.preventDefault();
alert($('#what').serialize());
});
检查hmm我不再使用ajax和jquery,因此我没有尝试过,但我知道abt phpsend可以告诉我们您想使用ajax发送的数据格式。@Lukedamczewski检查我的问题用户没有提到任何关于jquery的内容我有不同类型的单选按钮,具有不同的名称和值,以及不同类型的单选组例如,一旦我更新了Hi,我只需要检查我的问题,而不是发送所有的值,然后写下:如果(this.checked==true)array.push($(this.val())不起作用检查这个在你的fiddle代码中有2个语法错误,替换循环:$(“#what>input[type='radio'])。每个(函数(){if(this.checked==true){alert($(this.val())};})
theArray = theArray.join("##")
$('#what').on('submit', function(e) {
e.preventDefault();
alert($('#what').serialize());
});