【问题标题】:problem with ajax submission form when pressing enter回车时ajax提交表单的问题
【发布时间】:2011-11-15 01:46:03
【问题描述】:

我正在尝试在输入字段中提交一些文本并将其输出到同一页面上而不刷新页面。但是,它没有做我想做的事。我也有一个占位符元素,所以如果我不小心在该字段中输入任何内容,它不会将我的占位符文本插入到我的数据库(mysql)中。我遇到的问题是,当我按下回车键时,它只会刷新页面,而当我尝试在成功时收到警报时它不会提醒我。

--------------------下面的jquery ------------------

$('[placeholder]').parents('form').submit(function() {
  $(this).find('[placeholder]').each(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
    }

  });

  var input = $('input.to_do').val();

  dataList = 'list=' + input;
    $.ajax({
        type: "POST",
        url: "ajax_table_edit.php",
        data: dataList,
        cache: false,
        success: function(html)
            {
                alert(input);
                //$('.to_do_list_').html(data);
                //$('.n').hide();
            }
    });
});

--------------下面的html ------------------- -

<form action='#' method='post' >
<input type="text" class="to_do shadow" placeholder="enter text"/>
</form>

感谢您的宝贵时间!

【问题讨论】:

    标签: jquery ajax forms placeholder


    【解决方案1】:

    防止默认事件行为:

    $('[placeholder]').parents('form').submit(function(event) {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
    
      });
    
      var input = $('input.to_do').val();
    
      dataList = 'list=' + input;
        $.ajax({
            type: "POST",
            url: "ajax_table_edit.php",
            data: dataList,
            cache: false,
            success: function(html)
                {
                    alert(input);
                    //$('.to_do_list_').html(data);
                    //$('.n').hide();
                }
        });
    
        event.preventDefault();
    });
    

    【讨论】:

      【解决方案2】:

      在函数底部添加return false,这样页面就不会执行默认的提交操作。

      像这样:

      $('[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
          var input = $(this);
          if (input.val() == input.attr('placeholder')) {
            input.val('');
          }
      
        });
      
        var input = $('input.to_do').val();
      
        dataList = 'list=' + input;
          $.ajax({
              type: "POST",
              url: "ajax_table_edit.php",
              data: dataList,
              cache: false,
              success: function(html)
                  {
                      alert(input);
                      //$('.to_do_list_').html(data);
                      //$('.n').hide();
                  }
          });
      
        return false;
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-13
        • 2016-03-20
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 2015-09-26
        相关资源
        最近更新 更多