欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Ajax上傳實現(xiàn)根據(jù)服務(wù)器端返回數(shù)據(jù)進行js處理的方法

 更新時間:2015年07月31日 10:07:13   作者:akwolf  
這篇文章主要介紹了Ajax上傳實現(xiàn)根據(jù)服務(wù)器端返回數(shù)據(jù)進行js處理的方法,實例分析了Ajax請求及java處理并返回服務(wù)器端數(shù)據(jù)請求的相關(guān)技巧

本文實例講述了Ajax上傳實現(xiàn)根據(jù)服務(wù)器端返回數(shù)據(jù)進行js處理的方法。分享給大家供大家參考。具體如下:

Ajax上傳說白了還是使用form表單提交,在當(dāng)前頁面加一個iframe,將提交的內(nèi)容跳轉(zhuǎn)到iframe中,造成一種頁面無刷新的錯覺。

以前也做過上傳,基本是是使用commons-fileupload組件,基本的步驟是使用servlet處理完上傳之后,使用PrintWrite的對象實例輸出顯示內(nèi)容,可以是直接輸出內(nèi)容,也可以是輸出script進行操作如

復(fù)制代碼 代碼如下:
response.getWriter().write("<script type=\"text/javascript\"> parent.item_update.uploadUponSize();</script>");


復(fù)制代碼 代碼如下:
response.getWriter().write("上傳成功!");

這種做法是把對頁面端的操作都封裝到servlet中,現(xiàn)在一個需求是你接觸不到服務(wù)器端servlet,而上傳成功之后服務(wù)器只會返回一個標(biāo)志符,然后在頁面進行操作。
可以根據(jù)form表單提交到這個iframe時會觸發(fā)一個load事件,所以對于這個需求的思路是:

1、在form表單提交時,給iframe注冊load事件。

2、然后使用js對返回的標(biāo)志位進行判斷操作。

3、移除綁定事件,避免多次綁定事件。

下面貼一個例子。

對于服務(wù)器端簡單一點,只會返回一個標(biāo)志位。

package com.justsy.servlet; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
public class UploadServlet extends HttpServlet { 
  private static final long serialVersionUID = 1L; 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    this.doPost(request, response) ; 
  } 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    PrintWriter writer = response.getWriter() ; 
    response.setContentType("text/html") ; 
    writer.print("<root>ok</root>") ; 
  } 
} 

js文件

function submitForm(){ 
  $("#hidden_iframe").load(function(){ 
    var content = document.getElementById("hidden_iframe").contentWindow.document.body.innerHTML; 
    content = createXml(content); 
    var root = $(content).find("root").eq(0); 
    alert(root.text()); 
    $("#hidden_iframe").unbind("load"); 
  }); 
  document.getElementById("form2").submit(); 
} 
function createXml(str){ 
  if (document.all) { 
    var xmlDom = new ActiveXObject("Microsoft.XMLDOM"); 
    xmlDom.loadXML(str); 
    return xmlDom; 
  } 
  else { 
    return new DOMParser().parseFromString(str, "text/xml"); 
  } 
} 

html文件

<form action="uploadServlet.do" id="form2" enctype="multipart/form-data" method="post" target="hidden_iframe">
  <input type="hidden" name="method" value="uploadExcel" /><input type="button" value="Submit" onclick="submitForm()"/>
</form>
<iframe name="hidden_iframe" id="hidden_iframe" width="300" height="200">
</iframe>

這樣就可以根據(jù)頁面返回的內(nèi)容對頁面進行操作了。

希望本文所述對大家的Ajax程序設(shè)計有所幫助。

相關(guān)文章

最新評論