A-A+
简单的jquery无刷新表单提交实例
有了jquery要实现表单提交非常的简单,只需要一句话即可以实现了,下面小编来给各位整理两个无刷新表单提交实例,希望对各位有帮助。
例子1:
HTML文件,代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <script src="/jquery-latest.js"></script>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- </head>
- <body>
- <form action="" id="searchForm">
- 请输入一个数字,测试<input type="number" name="s" placeholder="Enter a number..." /> +
- <input type="number" name="b" placeholder="Enter a number..." />
- <input type="button" value="POST" id="su" />
- </form>
- <!-- the result of the search will be rendered inside this div -->
- <div id="result"></div>
- <script>
- $(function(){
- $("#su").click(function() {
- //var form = $('#searchForm').serialize();
- var s =$("input:[name=s]").val();
- var b =$("input:[name=b]").val();
- $.post("test.php",{s:s,b:b},function(data){
- $("#result").html(data)
- });
- // alert("fsdf");
- });
- });
- </script>
- </body>
- </html>
php文件:
- <?php
- //print_r($_POST);
- //$i = $_POST;
- $s = $_POST['s'];
- $b = $_POST['b'];
- $i = $s+$b;
- echo $i;
- ?>
例子2:
本例是用jquery.form.js form提交,action传递的
加了一个判断填写的项目是否填写
直接替换本页面ID
使用jquery.form.js
主要代码如下:
- <script src="../jquery.js"></script>
- <script src="jquery.form.js"></script>
- <script>
- // prepare the form when the DOM is ready
- $(document).ready(function() {
- // bind form using ajaxForm
- $('#htmlForm').ajaxForm({
- beforeSubmit:checkForm,//提交前运行函数验证
- // target identifies the element(s) to update with the server response
- target: '#htmlExampleTarget',
- // success identifies the function to invoke when the server response
- // has been received; here we apply a fade-in effect to the new content
- success: function() {
- $('#message').attr({"value":""});//内容提交后清空表单
- $('#htmlExampleTarget').fadeIn('slow');
- }
- });
- function checkForm(){
- if(document.htmlForm.bigclassid.value=="")
- {
- alert("Please choose product item");
- document.htmlForm.bigclassid.focus();
- $('#htmlForm').preventDefault();//阻止表单提交
- }
- }
- });
- </script>
- </head>
- <form id="htmlForm" action="ok.php" method="get" name="htmlForm">
- <input id="bigclassid" name="bigclassid">
- Message: <input type="text" name="message" value="" id="message"/>
- <input type="submit" value="ok" />
- </form>
- <div id="htmlExampleTarget">
- </div>