如何在不刷新的情况下使用jQuery提交表单?

时间:2011-05-23 16:12:50

标签: php jquery ajax forms post

我有这样的表格:

<form id="myform" name="myform" action="test.php" method="post">
<input type="text" name="shout-in" id="proShoutIn" maxlength="80" />
<a href="#" id="add_shout"><img src="post.gif"/></a>
</form>

我怎么能做一个ajax帖子才能使用if (isset($_POST['shout-in'])){..do something..}? 我需要获得在<input>中输入的值,然后用它做一个帖子。

任何想法? 感谢

4 个答案:

答案 0 :(得分:3)

$('#add_shout').click(function () {
    var $form=$('#myform');
    $.post($form.attr('action'), $form.serialize());
});
  • $.post() - {方法}的$.ajax()简写
  • .serialize() - 以标准网址编码表示法创建文本字符串

使用$.post()的第3个(可选)参数,您可以指定一个回调函数,该函数将接收作为唯一参数发回的任何内容。它将在AJAX查询成功完成时运行(因此您可以执行依赖于AJAX调用的DOM修改等)。

您也可能希望阻止默认表单提交(在很多浏览器中按输入字段中的Enter会触发它)并运行AJAX提交:

$('#myform').submit(function (e) {
     $('#add_shout').click();
     e.preventDefault();
});

答案 1 :(得分:1)

$.post("test.php", $("#myform").serialize(),
    function(data) {
      // do something with the response
    }
);

答案 2 :(得分:1)

   $("#myform").submit(function (e) {
      $.post(this.action, $(this).serialize(), function (data) {
         //handle response
      });
      //prevent form from submitting.  In jQuery, do not use return false
      e.preventDefault();
   }

答案 3 :(得分:0)