duangai1941 2016-06-08 20:38
浏览 35
已采纳

表单的ajax请求没有返回预期的数据

I have a form that contains checkboxes, radio buttons, and text area's. Then I have three buttons, regardless of what button is clicked it should call on the same php file to handle the form data. I need to keep track of which button is pressed, because the form data is handled differently depending on the button that is pressed.

I want this to update the page without reloading or redirecting and I am having trouble with getting the ajax to work properly. The php file just contains: "<pre><?php print_r($_POST); ?></pre> "at the moment, I will implement a switch-case after I have the basic functionality working.

When a button is clicked, a duplicate of the form is generated on the page instead of returning the POST values.

<form id="form" action="calc.php" method="post">
<input type="radio" name="rb[]" value="one" checked> one<br>
<input type="radio" name="rb[]" value="two">two<br>
Option a<input type="checkbox" name="cb[]" value="a">
Text a<input type="text" name="tb[]">
Option b<input type="checkbox" name="cb[]" value="b">
Text b<input type="text" name="tb[]">  
<button id="first" class="button" name="button[]" value="first">first</button>
<button id="second" class="button" name="button[]" value="second">second</button>
<button id="third" class="button" name="button[]" value="third">third</button>
</form>


<script>
$('.button').click(function(e) {
var f = $('form').serialize();
var b = this.id;
console.log(b);
console.log(f);
$.ajax({
    data: {'button':b, 'formval': f},
    type: $(this).attr('method'),
    url: $(this).attr('action'),
    success: function(resp){
        $('#result').html(resp);
}
});
return false;
});
</script>

How can I send the form values as an array along with the button that was clicked to the php file, and then have it return the result of the php file on the page?

Thank you.

  • 写回答

2条回答 默认 最新

  • douyi1855 2016-06-08 20:51
    关注

    You can use $.serializeArray and append to the returned array in the following manner:

    $('.button').click(function(e) {
        var $form = $('form');
        var data = $form.serializeArray();
    
        data.push({ 'name': 'button', 'value': this.id }); // append button's ID
    
        $.ajax({
            data: data,
            type: $form.attr('method'),
            url: $form.attr('action'),
            success: function(resp){
                $('#result').html(resp);
            }
        });
        return false; // I don't think this is needed since your button is type="button" 
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)