鑒于項目需要,開始邊看Demo邊使用JQuery。現將項目中暫時遇到的三種使用JQuery進行Ajax提交的方式做個總結。因為沒有系統學習,有點山寨,只求在項目中實現功能。
1.URL+GET參數提交
這種方式是最普遍的,只要包含jquery.js就可以正常使用。
Java代碼

- $.ajax({
- type: "get",
- url: "/openshop/control/getCustomerAddress",
- data:"customerId="+$.trim($("#customerId")[0].value),
- cache: false,
- success: function(msg){
- $("#addressInfo")[0].innerHTML = msg;
- showTipWindow(newid,oldid,0,e);
- }
- });
-
2.整個form的提交
如果不使用JQuery的form ajax提交,則必須手動組裝所有的表單元素鍵值對。現在使用JQuery的一個插件:jquery.form.js。將jquery.js,jquery.form.js文件都包含到項目中。然后使用如下代碼:
Java代碼

- $('#'+newid+'_frmNewAddr').ajaxForm({ beforeSubmit: validate ,success: showResponse});
-
- ....
-
- function validate(formData, jqForm, options){
- var form = jqForm[0];
- if (!form.new_recipient.value ) {
- alert('收件人必須填寫!');
- return false;
- }
- if (!form.new_address.value ) {
- alert('收件地址必須填寫!');
- return false;
- }
-
- ....
-
- return true;
- }
-
- function showResponse(responseText, statusText, xhr, $form){
- var address = eval("("+removeDivTag(responseText)+")");
- $("#address_recipient")[0].innerHTML = address.recipient;
- $("#address_address")[0].innerHTML = address.address;
- $("#address_organization")[0].innerHTML = address.organization;
- ......
- }
-
其中$('#'+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代碼

- <script type="text/javascript">
- function ajaxFileUpload(imgName)
- {
- $("#loading")
- .ajaxStart(function(){
- $(this).show();
- })
- .ajaxComplete(function(){
- $(this).hide();
- });
-
- $.ajaxFileUpload
- (
- {
- url:'/productmgr/control/uploadProductImg',
- secureuri:false,
- fileElementId: imgName+'File',
- dataType: 'text',
- success: function (data, status)
- {
- data = removeDivTag(data);
- if(data=="ImgEmptyErr"){
- alert("請選擇上傳圖片!");
- return;
- }
- if(data=="sysErr"){
- alert("上傳失敗,請重試!");
- return;
- }
- $("#"+imgName)[0].value = data;
- $("#"+imgName+"Div")[0].innerHTML = "上傳成功!"
- //alert($("#"+imgName)[0].value);
- },
- error: function (data, status, e)
- {
- alert("添加產品圖片時發生如下錯誤:"+e);
- }
- }
- )
- return false;
-
- }
- </script>
本人服務器端使用的是beanshell腳本,代碼如下:
Java代碼

- /*
- * 產品圖片上傳
- *
- * author : Emerson
- *
- * Yiihee , Inc. */
-
-
- import org.ofbiz.base.util.*;
- import org.ofbiz.base.util.string.*;
- import org.ofbiz.entity.*;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.io.*;
- import org.apache.commons.fileupload.disk.*;
- import org.apache.commons.fileupload.servlet.*;
- import org.apache.commons.fileupload.*;
-
-
- configProperties = UtilProperties.getProperties("opencommon.properties");
- String imageUploadServerPath = configProperties.get("openb2c.image.upload.server.path");
-
- //SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
- //Date date = new Date();
- //String filename = sf.format(date);
- String fileName;
-
- File uploadPath = new File(imageUploadServerPath);//上傳文件目錄
- if (!uploadPath.exists()) {
- uploadPath.mkdirs();
- }
- // 臨時文件目錄
- File tempPathFile = new File(imageUploadServerPath+"\\temp\\");
- if (!tempPathFile.exists()) {
- tempPathFile.mkdirs();
- }
- try {
- // Create a factory for disk-based file items
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- // Set factory constraints
- factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
- factory.setRepository(tempPathFile);//設置緩沖區目錄
-
- // Create a new file upload handler
- ServletFileUpload upload = new ServletFileUpload(factory);
-
- // Set overall request size constraint
- upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB
-
- List items = null;
- items = upload.parseRequest(request);//得到所有的文件
-
- if(items==null||items.size()==0){
- String msg = "ImgEmptyErr";
- context.put("result", msg);
- return;
- }
-
- Iterator i = items.iterator();
-
- //此處實際只有一個文件
- while (i.hasNext()) {
- FileItem fi = (FileItem) i.next();
- fileName = fi.getName();
- if (!UtilValidate.isEmpty(fileName)) {
- File fullFile = new File(fi.getName());
- //File fullFile = new File(filename);
- File savedFile = new File(uploadPath, fullFile.getName());
- int j = 0;
- while(savedFile.exists()){
- j++;
- savedFile = new File(uploadPath, savedFile.getName().substring(0,savedFile.getName().lastIndexOf(".")-1)+"("+j+")"+savedFile.getName().substring(savedFile.getName().lastIndexOf("."),savedFile.getName().length()));
- }
- fi.write(savedFile);
- fileName = savedFile.getName();
- }else{
- String msg = "ImgEmptyErr";
- context.put("result", msg);
- return;
- }
- }
- context.put("result", fileName);
- } catch (Exception e) {
- Debug.log("上傳產品圖片發生錯誤:"+e);
- String msg = "sysErr";
- context.put("result", msg);
- return;
- }
然后將result結果渲染到freemarker模板,并經回調函數解析后展示給用戶。
總結:JQuery強大異常,本文僅從自身使用角度列舉了其部分用法,未曾深究最新最優最簡用法,暫以此文作為經驗總結,以待日后參考修正。代碼片段山寨之處實屬本人技拙,而非JQuery之過。
posted on 2012-03-22 12:04
hellxoul 閱讀(7002)
評論(1) 編輯 收藏 所屬分類:
JavaScript