dreinuqm992401 2016-10-14 10:05
浏览 42
已采纳

Ajax表单发送错误

I'm have a form that sends data to a server. When the form is usual HTML it works fine. All data is sent to the server without error. However when I change the form to use AJAX I get an error.

<form id="form" action="handler.php" method="POST"> <!-- it's work -->
    <input id="contact_name" type="text" name="name" placeholder="NAME">
    <input id="contact_phone" type="text" name="phone" placeholder="PHONE">
    <button type="submit">Get call</button>
</form>
$(document).ready(function() {
    /*this does not work*/
    $('#form').on('submit', function(e) {
        var dataf = $(this).serialize();
        $.ajax({
            url: 'handler.php',
            type: 'POST',
            data: dataf,
            success: function(response) {
                console.log(JSON.stringify(response));
            },
            error: function(response) {
                console.log(JSON.stringify(response));
            }
        });
    });
});

In console I get this:

{"readyState":0,"responseText":"","status":0,"statusText":"error"} 
  • 写回答

2条回答 默认 最新

  • duanjue6584 2016-10-14 10:10
    关注

    You have to add e.preventDefault();

    $(document).ready(function(){/*this does not work*/
      $('#form').on('submit', function(e) {
        e.preventDefault();
        var dataf = $(this).serialize();
          $.ajax({
            url: 'handler.php',
            type: 'POST',
            data: dataf,
            success: function(response) {
              console.log(JSON.stringify(response));
            },
            error: function(response) {
              console.log(JSON.stringify(response));
            }
          });
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决