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条)

报告相同问题?

悬赏问题

  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率