鑒于項(xiàng)目需要,開(kāi)始邊看Demo邊使用JQuery。現(xiàn)將項(xiàng)目中暫時(shí)遇到的三種使用JQuery進(jìn)行Ajax提交的方式做個(gè)總結(jié)。因?yàn)闆](méi)有系統(tǒng)學(xué)習(xí),有點(diǎn)山寨,只求在項(xiàng)目中實(shí)現(xiàn)功能。
1.URL+GET參數(shù)提交
這種方式是最普遍的,只要包含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.整個(gè)form的提交
如果不使用JQuery的form ajax提交,則必須手動(dòng)組裝所有的表單元素鍵值對(duì)。現(xiàn)在使用JQuery的一個(gè)插件:jquery.form.js。將jquery.js,jquery.form.js文件都包含到項(xiàng)目中。然后使用如下代碼:
Java代碼

- $('#'+newid+'_frmNewAddr').ajaxForm({ beforeSubmit: validate ,success: showResponse});
-
- ....
-
- function validate(formData, jqForm, options){
- var form = jqForm[0];
- if (!form.new_recipient.value ) {
- alert('收件人必須填寫(xiě)!');
- return false;
- }
- if (!form.new_address.value ) {
- alert('收件地址必須填寫(xiě)!');
- 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')獲取表單對(duì)象,其中beforeSubmit對(duì)應(yīng)的validate()是一個(gè)表單提交前調(diào)用 的方法,可以在此方法中做表單驗(yàn)證,只有該方法返回true,表單才會(huì)提交。而success對(duì)應(yīng)的showResponse則是ajax對(duì)象成功返回后 的回調(diào)方法,可以將回調(diào)得到的內(nèi)容無(wú)刷新呈現(xiàn)到當(dāng)前頁(yè)面的相應(yīng)區(qū)域中。較方便的做法是在服務(wù)器端以JSON格式返回?cái)?shù)據(jù),然后在回調(diào)函數(shù)中使用 eval("("+removeDivTag(responseText)+")")方法獲取具有指定結(jié)構(gòu)的js對(duì)象。
3.使用JQuery做文件上傳的ajax提交
本人尋找并比較了多種ajax或類(lèi)ajax方式上傳文件的做法,譬如使用iframe等。最終覺(jué)得使用JQuery是最方便的,不知各位使用后是否與我有 同感。我將我目前的做法總結(jié)如下,首先須在項(xiàng)目中包含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("請(qǐng)選擇上傳圖片!");
- return;
- }
- if(data=="sysErr"){
- alert("上傳失敗,請(qǐng)重試!");
- return;
- }
- $("#"+imgName)[0].value = data;
- $("#"+imgName+"Div")[0].innerHTML = "上傳成功!"
- //alert($("#"+imgName)[0].value);
- },
- error: function (data, status, e)
- {
- alert("添加產(chǎn)品圖片時(shí)發(fā)生如下錯(cuò)誤:"+e);
- }
- }
- )
- return false;
-
- }
- </script>
本人服務(wù)器端使用的是beanshell腳本,代碼如下:
Java代碼

- /*
- * 產(chǎn)品圖片上傳
- *
- * 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();
- }
- // 臨時(shí)文件目錄
- 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); // 設(shè)置緩沖區(qū)大小,這里是4kb
- factory.setRepository(tempPathFile);//設(shè)置緩沖區(qū)目錄
-
- // Create a new file upload handler
- ServletFileUpload upload = new ServletFileUpload(factory);
-
- // Set overall request size constraint
- upload.setSizeMax(4194304); // 設(shè)置最大文件尺寸,這里是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();
-
- //此處實(shí)際只有一個(gè)文件
- 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("上傳產(chǎn)品圖片發(fā)生錯(cuò)誤:"+e);
- String msg = "sysErr";
- context.put("result", msg);
- return;
- }
然后將result結(jié)果渲染到freemarker模板,并經(jīng)回調(diào)函數(shù)解析后展示給用戶。
總結(jié):JQuery強(qiáng)大異常,本文僅從自身使用角度列舉了其部分用法,未曾深究最新最優(yōu)最簡(jiǎn)用法,暫以此文作為經(jīng)驗(yàn)總結(jié),以待日后參考修正。代碼片段山寨之處實(shí)屬本人技拙,而非JQuery之過(guò)。
posted on 2012-03-22 12:04
hellxoul 閱讀(7000)
評(píng)論(1) 編輯 收藏 所屬分類(lèi):
JavaScript