【问题标题】:jquery, send a form by staying on the same pagejquery,通过停留在同一页面上发送表单
【发布时间】:2013-03-12 10:08:34
【问题描述】:

我想在不离开当前页面的情况下发送表单,所以我正在使用:

$('.myForm').on('submit', function(){
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success: function(html) {
            alert('ok');
            }
        });
    return false; 
});

但它不起作用......请问有什么想法吗?

【问题讨论】:

  • 在什么情况下,'不起作用'?
  • 确保您的表单具有“myForm”类。
  • return false 在 jQuery 中表示 continue

标签: jquery ajax forms


【解决方案1】:

这样做:-

$(document).on('submit', '.myForm', function(e) {
     $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(html) {
        alert('ok');
        }
    });
    e.preventDefault();
});

【讨论】:

  • 需要在函数中实际传入event
  • 这仍将我带到一个新页面
  • @DanielCJacobs 您的 URL 将不在同一页面...
【解决方案2】:

这是一个例子

<form name="frm" method="POST" action="">
 <input type="text" name="name" id="name" value="" />
 <input type="text" name="last_name" id="last_name" value="" />
 <input type="submit" name="Update" id="update" value="Update" />
</form>

jquery部分

$("#update").click(function(e) {
  e.preventDefault();
  var name = $("#name").val(); 
  var last_name = $("#last_name").val();
  var dataString = 'name='+name+'&last_name='+last_name;
  $.ajax({
    type:'POST',
    data:dataString,
    url:'insert.php',
    success:function(data) {
      alert(data);
    }
  });
});

insert.php 页面

<?php
  $name = $_POST['name'];
  $last_name = $_POST['last_name'];
  $insert = "insert into TABLE_NAME values('$name','$last_name')";// Do Your Insert Query
  if(mysql_query($insert)) {
   echo "Success";
  } else {
   echo "Cannot Insert";
  }
?>

希望对你有帮助

【讨论】:

  • 我会选择这个作为最佳答案,尽管我更喜欢来自客户端(而不是 php)的用户反馈。
【解决方案3】:

使用event.preventDefault();

$('.myForm').on('submit', function(event){
    event.preventDefault(); 
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(html) {
        alert('ok');
        }
    });
    //return false; 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2015-01-02
    • 2016-01-21
    • 2023-03-15
    • 2011-08-09
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多