A-A+

简单的jquery无刷新表单提交实例

2016年01月08日 前端设计 暂无评论 阅读 5 views 次

有了jquery要实现表单提交非常的简单,只需要一句话即可以实现了,下面小编来给各位整理两个无刷新表单提交实例,希望对各位有帮助。

例子1:

HTML文件,代码如下:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.    
  5. <script src="/jquery-latest.js"></script>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  7. </head>  
  8. <body>  
  9.   <form action="" id="searchForm">  
  10.    请输入一个数字,测试<input type="number" name="s" placeholder="Enter a number..." /> +  
  11.    <input type="number" name="b" placeholder="Enter a number..." />  
  12.    <input type="button" value="POST" id="su" />  
  13.   </form>  
  14.   <!-- the result of the search will be rendered inside this div -->  
  15.   <div id="result"></div>  
  16.    
  17. <script>  
  18.  $(function(){  
  19.   $("#su").click(function() {   
  20.  //var form =  $('#searchForm').serialize();  
  21.  var s =$("input:[name=s]").val();  
  22.  var b =$("input:[name=b]").val();  
  23.  $.post("test.php",{s:s,b:b},function(data){   
  24.      $("#result").html(data)  
  25.    });  
  26.      // alert("fsdf");     
  27.   });  
  28.   });  
  29. </script>  
  30.    
  31. </body>  
  32. </html>  

php文件:

  1. <?php  
  2. //print_r($_POST);  
  3. //$i = $_POST;  
  4. $s = $_POST['s'];  
  5. $b = $_POST['b'];  
  6. $i = $s+$b;  
  7. echo $i;  
  8. ?>  

例子2:

本例是用jquery.form.js form提交,action传递的

加了一个判断填写的项目是否填写

直接替换本页面ID

使用jquery.form.js

主要代码如下:

  1. <script src="../jquery.js"></script>   
  2. <script src="jquery.form.js"></script>   
  3. <script>   
  4. // prepare the form when the DOM is ready   
  5. $(document).ready(function() {   
  6. // bind form using ajaxForm   
  7. $('#htmlForm').ajaxForm({   
  8. beforeSubmit:checkForm,//提交前运行函数验证  
  9. // target identifies the element(s) to update with the server response   
  10. target: '#htmlExampleTarget',  
  11.   
  12. // success identifies the function to invoke when the server response   
  13. // has been received; here we apply a fade-in effect to the new content   
  14. success: function() {   
  15. $('#message').attr({"value":""});//内容提交后清空表单  
  16. $('#htmlExampleTarget').fadeIn('slow');   
  17. }   
  18. });   
  19. function checkForm(){   
  20. if(document.htmlForm.bigclassid.value=="")  
  21. {  
  22. alert("Please choose product item");  
  23. document.htmlForm.bigclassid.focus();  
  24. $('#htmlForm').preventDefault();//阻止表单提交   
  25. }  
  26.   
  27. }  
  28.   
  29. });  
  30.   
  31. </script>   
  32. </head>  
  33.   
  34. <form id="htmlForm" action="ok.php" method="get" name="htmlForm">  
  35. <input id="bigclassid" name="bigclassid">  
  36. Message: <input type="text" name="message" value="" id="message"/>   
  37. <input type="submit" value="ok" />   
  38. </form>  
  39. <div id="htmlExampleTarget">  
  40. </div>  
标签:

给我留言