posts - 64,comments - 22,trackbacks - 0
          鑒于項目需要,開始邊看Demo邊使用JQuery。現(xiàn)將項目中暫時遇到的三種使用JQuery進行Ajax提交的方式做個總結(jié)。因為沒有系統(tǒng)學(xué)習(xí),有點山寨,只求在項目中實現(xiàn)功能。
              1.URL+GET參數(shù)提交
                 這種方式是最普遍的,只要包含jquery.js就可以正常使用。
               
          Java代碼  收藏代碼
          1. $.ajax({  
          2.     type: "get",  
          3.     url: "/openshop/control/getCustomerAddress",  
          4.     data:"customerId="+$.trim($("#customerId")[0].value),  
          5.     cache: false,  
          6.     success: function(msg){  
          7.           $("#addressInfo")[0].innerHTML = msg;  
          8.           showTipWindow(newid,oldid,0,e);  
          9.     }  
          10. });   
          11.      


              2.整個form的提交
                  如果不使用JQuery的form ajax提交,則必須手動組裝所有的表單元素鍵值對。現(xiàn)在使用JQuery的一個插件:jquery.form.js。將jquery.js,jquery.form.js文件都包含到項目中。然后使用如下代碼:
                
          Java代碼  收藏代碼
          1. $('#'+newid+'_frmNewAddr').ajaxForm({ beforeSubmit: validate ,success: showResponse});  
          2.   
          3. ....  
          4.   
          5. function validate(formData, jqForm, options){  
          6.     var form = jqForm[0];   
          7.     if (!form.new_recipient.value ) {   
          8.         alert('收件人必須填寫!');   
          9.         return false;   
          10.     }   
          11.     if (!form.new_address.value ) {   
          12.         alert('收件地址必須填寫!');   
          13.         return false;   
          14.     }   
          15.   
          16.    ....  
          17.   
          18.    return true;   
          19. }  
          20.   
          21. function showResponse(responseText, statusText, xhr, $form){  
          22.     var address = eval("("+removeDivTag(responseText)+")");   
          23.     $("#address_recipient")[0].innerHTML = address.recipient;  
          24.     $("#address_address")[0].innerHTML = address.address;  
          25.     $("#address_organization")[0].innerHTML = address.organization;  
          26.          ......  
          27. }  
          28.          

                其中$('#'+newid+'_frmNewAddr')獲取表單對象,其中beforeSubmit對應(yīng)的validate()是一個表單提交前調(diào)用 的方法,可以在此方法中做表單驗證,只有該方法返回true,表單才會提交。而success對應(yīng)的showResponse則是ajax對象成功返回后 的回調(diào)方法,可以將回調(diào)得到的內(nèi)容無刷新呈現(xiàn)到當(dāng)前頁面的相應(yīng)區(qū)域中。較方便的做法是在服務(wù)器端以JSON格式返回數(shù)據(jù),然后在回調(diào)函數(shù)中使用 eval("("+removeDivTag(responseText)+")")方法獲取具有指定結(jié)構(gòu)的js對象。

               3.使用JQuery做文件上傳的ajax提交
               本人尋找并比較了多種ajax或類ajax方式上傳文件的做法,譬如使用iframe等。最終覺得使用JQuery是最方便的,不知各位使用后是否與我有 同感。我將我目前的做法總結(jié)如下,首先須在項目中包含jquery.js,ajaxfileupload.js,ajaxfileupload.css。
          Java代碼  收藏代碼
          1. <script type="text/javascript">  
          2. function ajaxFileUpload(imgName)  
          3. {  
          4.     $("#loading")  
          5.     .ajaxStart(function(){  
          6.         $(this).show();  
          7.     })  
          8.     .ajaxComplete(function(){  
          9.         $(this).hide();  
          10.     });  
          11.   
          12.     $.ajaxFileUpload  
          13.     (  
          14.         {  
          15.             url:'/productmgr/control/uploadProductImg',  
          16.             secureuri:false,  
          17.             fileElementId: imgName+'File',  
          18.             dataType: 'text',  
          19.             success: function (data, status)  
          20.             {  
          21.                 data = removeDivTag(data);  
          22.                 if(data=="ImgEmptyErr"){  
          23.                     alert("請選擇上傳圖片!");  
          24.                     return;  
          25.                 }  
          26.                 if(data=="sysErr"){  
          27.                     alert("上傳失敗,請重試!");  
          28.                     return;  
          29.                 }  
          30.                 $("#"+imgName)[0].value = data;  
          31.                 $("#"+imgName+"Div")[0].innerHTML = "上傳成功!"  
          32.                 //alert($("#"+imgName)[0].value);  
          33.             },  
          34.             error: function (data, status, e)  
          35.             {  
          36.                 alert("添加產(chǎn)品圖片時發(fā)生如下錯誤:"+e);  
          37.             }  
          38.         }  
          39.     )     
          40.     return false;  
          41.   
          42. }  
          43. </script>  

                本人服務(wù)器端使用的是beanshell腳本,代碼如下:
          Java代碼  收藏代碼
          1. /* 
          2.  * 產(chǎn)品圖片上傳 
          3.  *  
          4.  * author : Emerson 
          5.  * 
          6.  * Yiihee , Inc. */  
          7.   
          8.   
          9. import org.ofbiz.base.util.*;  
          10. import org.ofbiz.base.util.string.*;  
          11. import org.ofbiz.entity.*;  
          12. import java.text.SimpleDateFormat;  
          13. import java.util.*;  
          14. import java.io.*;  
          15. import org.apache.commons.fileupload.disk.*;  
          16. import org.apache.commons.fileupload.servlet.*;  
          17. import org.apache.commons.fileupload.*;  
          18.   
          19.   
          20.     configProperties = UtilProperties.getProperties("opencommon.properties");  
          21.     String imageUploadServerPath = configProperties.get("openb2c.image.upload.server.path");  
          22.   
          23.     //SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");     
          24.     //Date date = new Date();     
          25.     //String filename = sf.format(date);  
          26.     String fileName;  
          27.   
          28.     File uploadPath = new File(imageUploadServerPath);//上傳文件目錄  
          29.     if (!uploadPath.exists()) {  
          30.        uploadPath.mkdirs();  
          31.     }  
          32.     // 臨時文件目錄  
          33.     File tempPathFile = new File(imageUploadServerPath+"\\temp\\");  
          34.     if (!tempPathFile.exists()) {  
          35.        tempPathFile.mkdirs();  
          36.     }  
          37.     try {  
          38.        // Create a factory for disk-based file items  
          39.        DiskFileItemFactory factory = new DiskFileItemFactory();  
          40.    
          41.        // Set factory constraints  
          42.        factory.setSizeThreshold(4096); // 設(shè)置緩沖區(qū)大小,這里是4kb  
          43.        factory.setRepository(tempPathFile);//設(shè)置緩沖區(qū)目錄  
          44.    
          45.        // Create a new file upload handler  
          46.        ServletFileUpload upload = new ServletFileUpload(factory);  
          47.    
          48.        // Set overall request size constraint  
          49.        upload.setSizeMax(4194304); // 設(shè)置最大文件尺寸,這里是4MB  
          50.    
          51.        List items = null;  
          52.        items = upload.parseRequest(request);//得到所有的文件  
          53.          
          54.        if(items==null||items.size()==0){  
          55.            String msg = "ImgEmptyErr";  
          56.            context.put("result", msg);  
          57.            return;  
          58.        }  
          59.          
          60.        Iterator i = items.iterator();  
          61.          
          62.        //此處實際只有一個文件  
          63.        while (i.hasNext()) {  
          64.            FileItem fi = (FileItem) i.next();  
          65.            fileName = fi.getName();  
          66.            if (!UtilValidate.isEmpty(fileName)) {  
          67.                File fullFile = new File(fi.getName());  
          68.                //File fullFile = new File(filename);  
          69.                File savedFile = new File(uploadPath, fullFile.getName());  
          70.                int j = 0;  
          71.                while(savedFile.exists()){  
          72.                    j++;  
          73.                    savedFile = new File(uploadPath, savedFile.getName().substring(0,savedFile.getName().lastIndexOf(".")-1)+"("+j+")"+savedFile.getName().substring(savedFile.getName().lastIndexOf("."),savedFile.getName().length()));  
          74.                }  
          75.                fi.write(savedFile);  
          76.                fileName = savedFile.getName();  
          77.            }else{  
          78.                String msg = "ImgEmptyErr";  
          79.                context.put("result", msg);  
          80.                return;  
          81.            }             
          82.        }  
          83.        context.put("result", fileName);  
          84.     } catch (Exception e) {  
          85.         Debug.log("上傳產(chǎn)品圖片發(fā)生錯誤:"+e);  
          86.         String msg = "sysErr";  
          87.         context.put("result", msg);  
          88.         return;  
          89.     }  

            然后將result結(jié)果渲染到freemarker模板,并經(jīng)回調(diào)函數(shù)解析后展示給用戶。

          總結(jié):JQuery強大異常,本文僅從自身使用角度列舉了其部分用法,未曾深究最新最優(yōu)最簡用法,暫以此文作為經(jīng)驗總結(jié),以待日后參考修正。代碼片段山寨之處實屬本人技拙,而非JQuery之過。   
          posted on 2012-03-22 12:04 hellxoul 閱讀(7002) 評論(1)  編輯  收藏 所屬分類: JavaScript

          FeedBack:
          # re: jquery Ajax 提交[未登錄]
          2014-08-28 19:13 | 111
          愛妃  回復(fù)  更多評論
            
          主站蜘蛛池模板: 南安市| 乐昌市| 昌平区| 昌都县| 米易县| 轮台县| 吉安县| 漾濞| 项城市| 台北县| 安图县| 黑河市| 甘南县| 邵武市| 郴州市| 琼结县| 米易县| 蓬莱市| 黑山县| 德钦县| 博罗县| 黄浦区| 通化县| 鲁甸县| 保康县| 健康| 镇巴县| 鄢陵县| 萨迦县| 桦甸市| 广东省| 石楼县| 邵阳县| 营山县| 巴彦淖尔市| 湖州市| 连平县| 东安县| 钦州市| 五指山市| 喜德县|