jsp+ajax實現無重新整理上傳檔案的方法_AJAX相關

來源:互聯網
上載者:User

本文執行個體講述了jsp+ajax實現無重新整理上傳檔案的方法。分享給大家供大家參考,具體如下:

列表頁:selectaddress.jsp
js頁:ajax_edit.js
jsp處理頁:editaddress.jsp
上傳工具類:UploadUtil.java

思想:由於安全問題,javascript操縱不了檔案, 導致ajax不能動態上傳檔案,所以選擇了iframe,

列表頁把form表單提交到一個隱式的iframe裡面,設定表單的屬性

複製代碼 代碼如下:
enctype='multipart/form-data'  target='hidden_frame'

然後,處理頁處理後返回
複製代碼 代碼如下:
out.println('<script>parent.callback(" 傳回值 ")</script>');

列表頁執行回呼函數!

selectaddress.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="com.wap3.navigater.service.*" %><%@ page import="com.wap3.navigater.dao.*" %><%@ page import="com.wap3.navigater.pojo.*" %><%@ page import="com.wap3.navigater.util.*" %><%@ page import="java.util.*" %><%@ page import="java.text.*" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="../js/jquery.js"></script><script type="text/javascript" src="../js/ajax_edit.js"></script><script type="text/javascript" src="../js/jquery.jclock.js"></script><script type="text/javascript" src="../js/common.js"></script><script type="text/javascript" src="../js/jquery.form.js"></script><script type="text/javascript" src="../js/fileTypeJudge.js"></script><script type="text/javascript" src="../js/jquery.datepick.js"></script><script type="text/javascript" src="../js/jquery.datepick-zh-CN.js"></script><link media=all href="../css/common.css" type=text/css rel=stylesheet><title>Insert title here</title><style type="text/css"> @import "inc/jquery.datepick.css";</style><script type="text/javascript">var $imgthis; $(function(){  var oldValue;  $(".package_list .edit").bind("dblclick",function(){   oldValue = $(this).text();   $(this).ajax_edit("editaddress.jsp",oldValue);  });  $(".package_list .edit_img").bind("dblclick",function(){ //   oldValue = $(this).html();   $imgthis = $(this);   $(this).parents("tr.package_list").siblings(".package_list").find(":input.cancel").trigger("click");   $(this).ajax_edit_img("editaddress.jsp",oldValue);  });  $(".package_list .edit :input[type!=file]:visible").live("blur",function(){   $(this).ajax_handle("editaddress.jsp?action=edit",oldValue);  });  $("#editcategoryName").live("change",function(){   $(this).ajax_handle("editaddress.jsp?action=edit",oldValue);  });  $("#del").click( function () {   if($(":checkbox.urlid:checked").size()>0){    var result = confirm("不可恢複的操作:確定要嗎?"+ '\n' +"提示:如果刪除大類會刪除大類及下面的子類!!!");    if (result) {     var url = location.href;     alert(url);     return ;     $(".main_table").wrap("<form id='selectAddressForm' action='selectaddress.jsp?action=del' method='post'></form>");     $("#selectAddressForm").submit();    }   }else{    alert("請選擇要刪除的項目!");    return false;   }  }); }); function callback(msg) //處理JSP回調 過來的參數 {  $imgthis.html("<img class='logo' src='"+msg+"' title='"+msg+"' />"); }</script></head><body> <%  String action = ParameterUtil.getStringParameter(request,"action","");  FriendurlDao friendurlDao = new IbatisFriendurlDao();  if("del".equals(action)){   int[] urlids = ParameterUtil.getIntArrayParams(request,"urlid");   for(int urlid : urlids){    friendurlDao.deleteFriendurlByP(urlid);   }  }  String navigaterPage = request.getRequestURL().toString();  if(request.getQueryString()!= null){   navigaterPage += "?"+request.getQueryString();  }  int categoryId = ParameterUtil.getIntParameter(request,"categoryId",0);  if(categoryId == 0){   response.sendRedirect("selectcategory.jsp");   return;  }  int pageSize = ParameterUtil.getIntParameter(request,"pageSize",10);  int pageNo = ParameterUtil.getIntParameter(request,"pageNo",1);  String orderBy = ParameterUtil.getStringParameter(request,"orderBy","sequence");  int ascOrDesc = ParameterUtil.getIntParameter(request,"ascOrDesc",0);  CategoryDao categoryDao = new IbatisCategoryDao();  Category category = categoryDao.selectCategoryByP(categoryId);  String categoryName = category.getCategoryName();  Friendurl friendurl = new Friendurl();  friendurl.setCategoryId(categoryId);  friendurl.addOrderBy(orderBy,ascOrDesc);  List<Friendurl> friendurlList = friendurlDao.selectFriendurlByE(friendurl);   //分頁  int totallpage = (int) Math.ceil(((double) friendurlList .size() * 1.0D)/ (double) pageSize);  pageNo =pageNo <= 0 ? 1 : pageNo;  pageNo =pageNo > totallpage ? totallpage : pageNo;  DataPageUtil datePage = new DataPageUtil(friendurlList ,friendurlList .size(),pageSize, pageNo);  boolean hasPrerPage = datePage.hasPrevPage();  boolean hasNextPage= datePage.hasNextPage();  int curpageNo = datePage.getPageNo();  int pageCount = datePage.getPageCount();  friendurlList = DataPageUtil.subList(friendurlList, pageSize, pageNo);  if(friendurlList == null && friendurlList.size()<=0) {   out.println("沒有您需要的資料");  }else{  %>  <%@include file="inc/header.jsp" %> <div id = "mainbox">  <div class = "c1">   <table class="main_table" width="100%" border="1" cellspacing="0" cellpadding="0">    <tr>     <th align="center" height="20" colspan="13" align="center" bgcolor="#006699">條目列表</th>    </tr>    <tr>     <td width="10%" height="20" align="center" bgcolor="#009999">      <input id="AllORNoall" type="checkbox"><label for="AllORNoall">全選</label>      <input type="button" id="reserse" value="反選" />     </td>     <td width="7%" height="20" align="center" bgcolor="#009999">網站名稱</td>     <td width="7%" height="20" align="center" bgcolor="#009999">網站別名</td>     <td width="7%" height="20" align="center" bgcolor="#009999">歸類</td>     <td width="7%" height="20" align="center" bgcolor="#009999">公司地址</td>     <td width="7%" height="20" align="center" bgcolor="#009999">文字連結</td>     <td width="7%" height="20" align="center" bgcolor="#009999">圖片連結</td>     <td width="7%" height="20" align="center" bgcolor="#009999">描述</td>     <td width="7%" height="20" align="center" bgcolor="#009999">有效開始時間</td>     <td width="7%" height="20" align="center" bgcolor="#009999">有效結束時間</td>     <td width="7%" height="20" align="center" bgcolor="#009999">電話</td>     <td width="7%" height="20" align="center" bgcolor="#009999">位置排序</td>     <td width="7%" height="20" align="center" bgcolor="#009999">推薦序號</td>    </tr>    <%     for(Friendurl friendurlTemp:friendurlList) {      int urlId = friendurlTemp.getUrlid();      String siteName = friendurlTemp.getSitename();      String alias = friendurlTemp.getAlias();      String address = friendurlTemp.getAddress();      String texturl = friendurlTemp.getTexturl();      String imageurl = friendurlTemp.getImageurl();      String description = friendurlTemp.getDescription();      Date validbegintime = friendurlTemp.getValidbegintime();      Date validendtime = friendurlTemp.getValidendtime();      String mobile = friendurlTemp.getMobile();      int sequence = friendurlTemp.getSequence();      int filter = friendurlTemp.getFilter();     %>    <tr class="package_list">     <td height="20" align="center" class="urlid_td"><input type="checkbox" name="urlid" class="id_select urlid" value=<%= urlId%> /></td>     <td height="20" align="center" class="edit sitename"><%=siteName %></td>     <td height="20" align="center" class="edit alias"><%=alias %></td>     <td height="20" align="center" class="edit categoryName"><%=categoryName%></td>     <td height="20" align="center" class="edit address"><%=address %></td>     <td height="20" align="center" class="edit texturl"><%=texturl%></td>     <td height="20" align="center" class="edit_img imageurl"><img src='<%=imageurl%>' class='logo' title='<%=imageurl%>'/></td>     <td height="20" align="center" class="edit description"><%=description%></td>     <td height="20" align="center" class="edit validbegintime"><%=validbegintime == null || "".equals(validbegintime)? "--:--" : TimeUtil.date2Str(validbegintime)%></td>     <td height="20" align="center" class="edit validendtime"><%=validendtime == null || "".equals(validendtime)? "--:--" : TimeUtil.date2Str(validendtime)%></td>     <td height="20" align="center" class="edit mobile"><%=mobile%></td>     <td height="20" align="center" class="edit sequence"><%=sequence%></td>     <td height="20" align="center" class="edit filter"><%=filter%></td>    </tr>    <%     }     %>    <tr>     <td align="center"><input type="button" id="del" value="刪除" /></td>     <td align="center" colspan = "12">提示:雙擊選框修改屬性值</td>    </tr>   </table>  </div>  <%@ include file="inc/pagination.jsp"%> </div> <%  }  %><iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe></body></html>

editaddress.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="com.wap3.navigater.util.*" %><%@ page import="com.wap3.navigater.service.*" %><%@ page import="com.wap3.navigater.pojo.*" %><%@ page import="com.wap3.navigater.dao.*" %><%@ page import="java.util.*" %><%@ page import="java.text.*" %> <%  String target = ParameterUtil.getStringParameter(request,"target","");  String action = ParameterUtil.getStringParameter(request,"action","");  if(!"".equals(target) && target != null && "edit".equals(action)){   int categoryId = 0;   CategoryDao categoryDao = null;   int urlid=0,status=0,sequence=0,filter=0;   String sitename=null,alias=null,texturl=null,imageurl=null,description=null,mobile=null;   Date validbegintime=null,validendtime=null;   if("imageurl".equals(target)){    System.out.println("圖片上傳");    UploadUtil.upload(request, response);    String imageurlpath = (String) request.getAttribute("imageurlpath");    urlid = Integer.parseInt((String)request.getAttribute("urlid"));    imageurl = (String)request.getAttribute("imageurlpath");   }else{    if("categoryName".equals(target)){     String categoryName = ParameterUtil.getStringParameter(request,"categoryName","");     Category category = new Category();      category.setCategoryName(categoryName);     categoryDao = new IbatisCategoryDao();     Category category2 = categoryDao.selectCategoryByE(category).get(0);      categoryId = category2.getCategoryId();    }else{     categoryId = ParameterUtil.getIntParameter(request,"categoryId",0);    }     urlid = ParameterUtil.getIntParameter(request,"urlid",0);     sitename = ParameterUtil.getStringParameter(request,"sitename","");     alias = ParameterUtil.getStringParameter(request,"alias","");     texturl = ParameterUtil.getStringParameter(request,"texturl","");     imageurl = ParameterUtil.getStringParameter(request,"imageurl","");     description = ParameterUtil.getStringParameter(request,"description","");     status = ParameterUtil.getIntParameter(request,"status",0);     sequence = ParameterUtil.getIntParameter(request,"sequence",0);     filter = ParameterUtil.getIntParameter(request,"filter",0);     mobile = ParameterUtil.getStringParameter(request,"mobile","");     validbegintime = ParameterUtil.getDateParameter(request,"validbegintime");     validendtime = ParameterUtil.getDateParameter(request,"validendtime");   }   Calendar beginDay=Calendar.getInstance();   Friendurl friendurl = new Friendurl();    friendurl.setUrlid(urlid);    friendurl.setSitename(sitename);    friendurl.setDescription(description);    friendurl.setTexturl(texturl);    friendurl.setImageurl(imageurl);    friendurl.setAlias(alias);    friendurl.setSequence(sequence);    friendurl.setMobile(mobile);    friendurl.setCategoryId(categoryId);    friendurl.setStatus(status);    friendurl.setValidbegintime(validbegintime);    friendurl.setValidendtime(validendtime);    friendurl.setFilter(filter);   FriendurlDao friendurlDao = new IbatisFriendurlDao();   friendurlDao.updateFriendurlByP(friendurl);   Friendurl friendurl2 = friendurlDao.selectFriendurlByE(friendurl).get(0);   if(friendurl2 != null){    String methodName = "get" + target.substring(0,1).toUpperCase()+target.substring(1);    if(target.endsWith("time")){     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");     out.println(TimeUtil.date2Str(((Date)(friendurl2.getClass().getMethod(methodName,new Class[]{}).invoke(friendurl2,new Object[]{})))));    }else if("categoryName".equals(target)){     out.println(categoryDao.selectCategoryByP(friendurl2.getCategoryId()).getCategoryName());    }else if("imageurl".equals(target)){     // 無重新整理關鍵的步驟,讓iframe的父輩body執行callback這個函數     out.println("<script>parent.callback('"+friendurl2.getClass().getMethod(methodName,new Class[]{}).invoke(friendurl2,new Object[]{})+"')</script>");    }else{     out.println(friendurl2.getClass().getMethod(methodName,new Class[]{}).invoke(friendurl2,new Object[]{}));    }   }else{    out.println("更新失敗");   }  }%>

ajax_edit.js

(function(){  $.fn.extend({   ajax_edit:function(str,oldValue){    return this.each(function(){     $this = $(this);     var id;     var nameId = $this.attr("class").split(" ")[1];     var idName = $this.parents("tr.package_list").find("td:first-child :input[type=checkbox]").attr("class").split(" ")[1];     id = $this.siblings("."+idName+"_td").find("input").val();     if(nameId == "categoryName" && str == "editaddress.jsp"){      $this.load("categorylist.jsp",{'oldValue':oldValue,'urlid':id});     }else{      $this.html("<form id='selectaddressForm'><input type='hidden' name='"+idName+"' value='"+id+"' /><input type='hidden' name='target' value='"+nameId+"' /><input type='text' name='"+nameId+"' value='"+oldValue+"'/></form>");      $this.find(":input:last").focus();     }    })   },  ajax_edit_img:function(str,oldValue){ //處理圖片上傳AJAX 關鍵的一步form表格裡的 target='hidden_frame'提交到ID為hidden_frame的iframe裡面   return this.each(function(){    var $this = $(this);    var nameId = $this.attr("class").split(" ")[1];    var idName = $this.parents("tr.package_list").find("td:first-child :input[type=checkbox]").attr("class").split(" ")[1];    var id = $this.siblings("."+idName+"_td").find("input").val();    var $imgForm = $("<form id='selectaddressForm_img' action='editaddress.jsp?action=edit&target=imageurl' method='post' enctype='multipart/form-data' target='hidden_frame'><input type='hidden' name='"+idName+"' value='"+id+"' /><input type='file' name='"+nameId+"' /><input type='button' class='cancel' value='取消' /><input type='button' class='ok' value='上傳' /></form>");    $this.html($imgForm);    $this.find(":input:last").focus();    $imgForm.find(":input[type=file]").bind("change",function(){     $(this).fileTypeJudge("photo");    })    $imgForm.find(":input.ok").bind("click",function(){     var $button = $(this);     if($imgForm.find(":input[type=file]").val()==''){      alert("請上傳圖片!");      return false;     }     $button.attr("disabled",true);     $("#selectaddressForm_img").submit();    })    $imgForm.find(":input.cancel").bind("click",function(){     $(this).parents(".edit_img").html(oldValue);    });   })  },  ajax_handle:function(str,oldValue){    return this.each(function(){     var $this = $(this);     setTimeout(function(){     if(!$("div").hasClass("datepick-control") || !$("div .datepick-control").is(":visible")){      if(oldValue != $this.val() && $this.val() !="" ){         $.post(          str,$("#selectaddressForm").serialize(),          function(data){           $this.parents(".edit").text(data.trim()).css("color","red");          }         )      }else{       $this.parents(".edit").text(oldValue);      }     }     },1000);    })   }  })})(jQuery)

希望本文所述對大家ajax程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.