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

如果提交一個表單而不刷新整個頁面,我們首先想到的是$.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);

搞定,有了這個就可以做出進度條等稍微複雜的功能啦~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章