posts - 64,comments - 22,trackbacks - 0
          鑒于項目需要,開始邊看Demo邊使用JQuery。現將項目中暫時遇到的三種使用JQuery進行Ajax提交的方式做個總結。因為沒有系統學習,有點山寨,只求在項目中實現功能。
              1.URL+GET參數提交
                 這種方式是最普遍的,只要包含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提交,則必須手動組裝所有的表單元素鍵值對。現在使用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對應的validate()是一個表單提交前調用 的方法,可以在此方法中做表單驗證,只有該方法返回true,表單才會提交。而success對應的showResponse則是ajax對象成功返回后 的回調方法,可以將回調得到的內容無刷新呈現到當前頁面的相應區域中。較方便的做法是在服務器端以JSON格式返回數據,然后在回調函數中使用 eval("("+removeDivTag(responseText)+")")方法獲取具有指定結構的js對象。

               3.使用JQuery做文件上傳的ajax提交
               本人尋找并比較了多種ajax或類ajax方式上傳文件的做法,譬如使用iframe等。最終覺得使用JQuery是最方便的,不知各位使用后是否與我有 同感。我將我目前的做法總結如下,首先須在項目中包含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("添加產品圖片時發生如下錯誤:"+e);  
          37.             }  
          38.         }  
          39.     )     
          40.     return false;  
          41.   
          42. }  
          43. </script>  

                本人服務器端使用的是beanshell腳本,代碼如下:
          Java代碼  收藏代碼
          1. /* 
          2.  * 產品圖片上傳 
          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); // 設置緩沖區大小,這里是4kb  
          43.        factory.setRepository(tempPathFile);//設置緩沖區目錄  
          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); // 設置最大文件尺寸,這里是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("上傳產品圖片發生錯誤:"+e);  
          86.         String msg = "sysErr";  
          87.         context.put("result", msg);  
          88.         return;  
          89.     }  

            然后將result結果渲染到freemarker模板,并經回調函數解析后展示給用戶。

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

          FeedBack:
          # re: jquery Ajax 提交[未登錄]
          2014-08-28 19:13 | 111
          愛妃  回復  更多評論
            
          主站蜘蛛池模板: 岳西县| 若尔盖县| 察隅县| 中江县| 大悟县| 积石山| 宝丰县| 邯郸县| 平江县| 宜川县| 临湘市| 盐源县| 古蔺县| 彰化市| 苏尼特左旗| 腾冲县| 永福县| 云梦县| 尤溪县| 苏州市| 辉南县| 扎鲁特旗| 永新县| 辽源市| 乌拉特前旗| 西乌| 普定县| 禹城市| 曲阳县| 密云县| 寿光市| 乌恰县| 大田县| 班戈县| 包头市| 汶上县| 吉安市| 普宁市| 武鸣县| 姚安县| 新晃|