当前位置: 代码迷 >> Ajax >> JQuery的Ajax交付
  详细解决方案

JQuery的Ajax交付

热度:810   发布时间:2012-11-05 09:35:12.0
JQuery的Ajax提交
    鉴于项目需要,开始边看Demo边使用JQuery。现将项目中暂时遇到的三种使用JQuery进行Ajax提交的方式做个总结。因为没有系统学习,有点山寨,只求在项目中实现功能。
    1.URL+GET参数提交
       这种方式是最普遍的,只要包含jquery.js就可以正常使用。
     
  
			$.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文件都包含到项目中。然后使用如下代码:
      
$('#'+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。
<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脚本,代码如下:
/*
 * 产品图片上传
 * 
 * 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之过。   


  相关解决方案