输入按钮未使用AJAX提交 [英] Input button not submitting with AJAX
问题描述
php我有以下代码
<form id="one" method="POST" action="#">
<input type="text" name="rfc" />
<button type="submit" name="selection" value="1">Option 1 </button>
<button type="submit" name="selection" value="2">Option 2 </button>
<input type="submit" name="selection" value="4" />
</form>
<section id="new_section"></section>
<script>
$('#one').submit(function(event){
var data = $(this).serialize();
$.post('two.php', data)
.success(function(result){
$('#new_section').html(result);
})
.error(function(){
console.log('Error loading page');
})
return false;
});
</script>
在two.php中我验证了rfc和选择字段的值
In two.php I verify the values of rfc and selection fields
two.php
print_r($_POST);
而print_r只显示rfc而不是选择,输出如下:
And print_r only shows the rfc but not the selection , the output is the following:
数组([rfc] => WIRK510828)
Array ( [rfc] => WIRK510828 )
这是因为action =#?
Is this happening because of the action=# ?
推荐答案
这是因为你应该单独传递按钮的值,因为serialize()没有取按钮值。
It's because you should pass the button's values separately, because the serialize() doesn't take the buttons values.
首先你要为每个按钮添加和ID或类
使用 serializeArray();
而不是 serialize()
。
first you have add and id or class to each button
Use serializeArray();
instead of serialize()
.
在你的html上执行类似这样的操作,它有效我刚测试了它:
do something like this on your html, it works I just tested it:
<form id="one" method="POST" action="#">
<input type="text" name="rfc" />
<button type="submit" id="button1" name="selection" value="1">Option 1 </button>
<button type="submit" id="button2" name="selection" value="2">Option 2 </button>
<button type="submit" id="button4" name="selection" value="4">option 4</button>
</form>
<section id="new_section"></section>
<script>
var frm = $('#one');
var data = frm.serializeArray();
$('#button1, #button2, #button4').on("click",function(e) {
e.preventDefault();
frm.submit(function(event){
$.post('two.php', data)
.success(function(result){
$('#new_section').html(result);
})
.error(function(){
console.log('Error loading page');
})
return false;
});
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
frm.submit();
data.pop();
});
</script>
说明:
我使用 data.push();
将extradata(按钮值)推送到 serializeArray();
然后使用 frm.submit()
发送表单,最后 data.pop()
清理数组以备将来使用。我还添加了一些变量以便更好地实现。
explanation:
I use the data.push();
to push the extradata (the buttons values) into the serializeArray();
then use frm.submit()
to send the form and finally data.pop()
to clean the array for future uses. I have also added some variables for better implementation.
这篇关于输入按钮未使用AJAX提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!