douzhan3900 2017-08-24 21:01
浏览 109


I have a form in which currently posts to a hard coded php page in the action of the form, this works fine, it posts to the DB no problem, but where things get tricky for me is I don't want to post to a new page so I have opted to use ajax. So I got rid of the action field from the form and put in some jquery to make an ajax call. the issues I am having is doesn't work :D. Could someone take a look at my js file and explain to me what I am doing wrong or what I should do?

<script src="" type="text/javascript">

      <textarea name= "comment" rows="6" cols="50"></textarea><br />
      <input type="submit" name= "submit" value="submit" id = "submit">

            type        : 'POST',
            url         : 'comment.php',
            data        : formData,
            dataType    : 'json',

  • 写回答

1条回答 默认 最新

  • duanpo2037 2017-08-24 22:16

    You should handle the 'submit' event of the form over the 'click' event of the submit button. You should also return false; at the end of function to prevent the form from posting to a new page. You are handling the submit yourself. Also I would put the action attribute back on the form element for the rare occasion that JavaScript is disabled on the client. Give the form an id and target that. Your code is correct otherwise.


        <form id="my-form" action="comment.php" method="post">
            <!-- input fields -->


        $('#my-form').on('submit', function(){ 
            // code...
            return false;

    Providing the action attribute, as well as the method attribute, on the form element will make these available to access in your submit handler as well as providing a proper fallback for any JavaScript failures. That may not be necessary for this instance but may be helpful in the future.

    Your handler could now look something like this:


        $('#my-form').on('submit', function(){ 
            // serialize the form
            var formData = $(this).serialize();
                type        : this.method,
                url         : this.action,
                data        : formData,
                dataType    : 'json'
            .done(function (data) { 
                // do some stuff with 'data'
            .fail(function (error) {
                // do some stuff with 'error'
            return false;
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥20 matlab可以把多个二维图合成为三维瀑布图吗
  • ¥15 EEPROM,软件i2c
  • ¥500 求解读该段JS代码,需要知道是用干什么的
  • ¥20 qt4代码实现二进制文件读取显示,以及显示的内容进行搜索
  • ¥15 Labview获取LK-G3001数据
  • ¥15 我知道什么是混合树,但是怎么写代码啊
  • ¥50 开发板linux系统安装dpkg,apt函数库 有偿
  • ¥15 浏览器时间循环 交互事件和延时事件的 优先级与执行问题
  • ¥15 GD模块安装出错,libgd无法正常安装
  • ¥20 求有缘人帮我把笛卡尔坐标系转换为经纬度 有偿