jquery.form.js ajaxSubmit()使用案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhouchenxuan/article/details/71213739

如果提交一个表单而不刷新整个页面,我们首先想到的是$.ajax()方法,下面我们来介绍另一个方法,就是jquery.form.js插件下的ajaxForm()方法和ajaxSubmit()方法。

  • 先引入资源

注意顺序不能错。

<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-form.js"></script>
  • 然后写html代码
<form id="myform" method="post" action="AjaxForm">
    <table align="center">
        <tr>
            <td>卡号:</td>
            <td><input type="text" id="code" value="1" name="code" /></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" id="pwd" value="111111" name="pwd" /></td>
        </tr>
        <tr>
            <td>余额:</td>
            <td><div id="input" ></div>(元)</td>
        </tr>
        <tr>
            <td colspan="2"><input type="button" id="check" value="查询余额"></td>
        </tr>
    </table>
</form>

效果图:
这里写图片描述
假定输入完卡号和密码,点击“查询余额”按钮,页面不刷新的情况下查询余额并显示在对应位置,如下图:

这里写图片描述
效果不是太好(忍了。。。)

  • 接着写js代码
<script type="text/javascript">
$(function(){
    $('#check').bind("click", function(){  
        $('#myform').ajaxSubmit(options);
    });
})
var options = {  
           //target: '#input',          //把服务器返回的内容放入id为input的元素中      
           beforeSubmit: showRequest,  //提交前的回调函数  
           success: showResponse,      //提交后的回调函数  
           //url: url,                 //默认是form的action, 如果申明,则会覆盖  
           //type: type,               //默认是form的method(get or post),如果申明,则会覆盖  
           //dataType: null,           //html(默认), xml, script, json...接受服务端返回的类型  
           //clearForm: true,          //成功提交后,清除所有表单元素的值  
           //resetForm: true,          //成功提交后,重置所有表单元素的值  
           //timeout: 3000               //限制请求的时间,当请求大于3秒后,跳出请求  
        }  

        function showRequest(formData, jqForm, options){  
           //formData: 数组对象,提交表单时,Form插件会以Ajax方式自动提交这些数据,
           //格式如:[{name:'code',required:false,type:'text',value:'1' },{name:'pwd',required:false,type:'password',value:'111111' }]

           //jqForm:   jQuery对象,封装了表单的元素     
           //options:  options对象  
           var queryString = $.param(formData);   //code=1&pwd=111111  
           var formElement = jqForm[0];              //将jqForm转换为DOM对象  
           var address = formElement.code.value;  //1  
           return true;  //只要不返回false,表单都会提交,在这里可以对表单元素进行验证  
        };  

        function showResponse(responseText, statusText){//responseText:后台返回的数据;  statusText:状态,成功时返回success
            $('#input').html(responseText);
        };  
</script>
  • 最后后台代码没啥可说的。
String code = request.getParameter("code").toString();
        int a = code.equals("1")?100:200;
        String s = String .valueOf(a);
        response.getWriter().write(s);

搞定,有了这个就可以做出进度条等稍微复杂的功能啦~

猜你喜欢

转载自blog.csdn.net/zhouchenxuan/article/details/71213739
今日推荐