2010-09-20 197 views
2

有人可以教我如何使用jquery来显示成功的表单提交而不刷新页面。 类似的情况发生在gmail上,当一个消息被传递时,黄色覆盖图显示你的消息已经被传递,然后淡出。jquery表单提交

+1

,你甚至尝试谷歌? – zerkms 2010-09-20 04:28:24

+0

试试这个http://jquery.malsup.com/form/。这是我以前在我的项目中使用的 – svk 2010-09-20 04:30:51

+0

有趣的zerkms ...我google了很多,但没有找到我正在寻找的4r – Ayush 2010-09-20 04:32:14

回答

2

使用jQuery + JSON组合是这样的:

test.php的:

<script type="text/javascript" src="jquery-1.4.2.js"></script> 
<script type="text/javascript" src="jsFile.js"></script> 

<form action='_test.php' method='post' class='ajaxform'> 
<input type='text' name='txt' value='Test Text'> 
<input type='submit' value='submit'> 
</form> 

<div id='testDiv'></div> 

_test.php:

<?php 
     // Code here to deal with your form submitted data. 
     $arr = array('testDiv' => 'Form is successfully submitted.'); 
     echo json_encode($arr); 
?> 

jsFile.js:

jQuery(document).ready(function(){ 

    jQuery('.ajaxform').submit(function() { 

     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         for(var id in data) { 
          jQuery('#' + id).html(data[id]); 
         } 
         } 
     }); 

     return false; 
    }); 

}); 




OR:

您可以使用jQuery Form Plugin

+0

上面这段代码昨天工作正常,但今天发生了奇怪的事情。而不是将** testDiv **的内容与页面的内容一起添加到test.php中,并在空白页面中显示{testdiv =>“deliver”}。 – Ayush 2010-09-21 08:48:18

+0

@Ayush:你昨天的代码改变了什么。它显示JSON数据('{testdiv =>“已传递”}“),因为以下可能的原因:** 1。**可能是您的jQuery函数未被调用,因为您已经移除了'class ='来自'form'标记的ajaxform'',用于捕获jQuery代码中的提交事件。 ** 2。**可能是你改变了'jQuery('.ajaxform')。submit(.....)'中的选择器('.ajaxform')。 ** 3。**可能是你没有正确包含jQuery代码/文件。 – NAVEED 2010-09-21 15:13:44

+0

当我检查使用Firebug它表明我 - POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php \t 404未找到1.26s \t jquery.min.js (130行)我已经检查过sms.php的地址是否正确 – Ayush 2010-09-23 09:00:42