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 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名