2010-11-28 102 views
0

我正在使用JavaScript。我使用iframe將文件上傳到servlet。我使用正確接收該帖子的java servlet並返回一個gson對象。但是我無法從iframe中訪問返回的對象。如何從iFrame訪問servlet結果?

這裏是形式

<form name='myform' id='myform' method="POST" enctype="multipart/form-data" action="http://localhost:9090/myServlet" target="myFrame" > 
<td> <input type="file" size=20 name="fname"> </td> 
<td> <input type="Submit" value="Upload"> </td> </form> 
</tr></table> 
<iframe src="" id="myFrame" name="myFrame" style="width: 110px; height: 110px;"> 
    <script type="text/javascript"> 
    var accountList=null; 
    </script> 
</iframe> 

在servlet做任何需要並返回

> response.setContentType("text/html"); 
    > response.getWriter().println("<html><body 
    > onload=\"window.parent.uploadComplete();\">"+ 
    >      "<div id='resu' name='resu'>" + 
    >      gsonTable+ 
    >      "</div>"+ 
    >      "</body></html>");  response.getWriter().close(); 

其中gsonTable爲{ 「暱稱」: 「defaultStatname」, 「日期」:「1/1/2010 /「}

我該如何讓gson對象脫離div?

在我的功能

function uploadComplete() { 
    var frame=parent.document.getElementById('myFrame'); 
    var pippo=frame.contentDocument; 
    var div = pippo.getElementById('resu'); 
    var myvar=div.innerHTML; 
    myvar=eval(myvar); } 

當我執行的eval(MYVAR)我得到「無效的標籤」 我,因爲作爲一個GSON對象應該是罰款EVAL字符串頗爲驚訝。 我確定我在某個地方犯了一個錯誤,但我找不到它。也許我不應該在div中存儲gson對象,並且有更好的解決方案。 任何幫助將是偉大的 /f

回答

0

我找到了解決方案。我想我在這裏很天真。 我在iframe中聲明瞭一個變量,並將它在servlet中分配給iFrame html中的gson變量。然後我讀取uploadComplete函數中的變量。這是

<form name='myform' id='myform' method="POST" enctype="multipart/form-data" action="http://localhost:9090/bankUI/loadaccountstatement" target="myFrame" > 
<td> <input type="file" size=20 name="fname"> </td> 

<td> <input type="Submit" value="Upload"> </td> </form> 
</tr></table> 
<iframe src="" id="myFrame" name="myFrame" style="width: 110px; height: 110px;"> 
    <script type="text/javascript"> 
    var newStatement; 
    </script> 
</iframe> 

servlet代碼:

response.setContentType("text/html"); 
         response.getWriter().println("<html><body onload=\"window.parent.uploadComplete();\">"+ 
           "<script type=\"text/javascript\">" + 
           "parent.document.newStatement = "+gsonTable+";" + 
           "</script>"+ 
           "<div> </div>"+ 
           "</body></html>"); 
         response.getWriter().close(); 

功能

function uploadComplete() { 
    //the variable newStatement in the iframe containing the returned variable 
    var stat=parent.document.newStatement; 
    //assigning a variable in the general context 
    var myVar=this.currentSession=stat; 

}