form.submit()發送請求一般是單向的,如果需要取返回的數據,一般會發送ajax請求,但是如果form中有附件呢?(以后有時間給大家分享ajax上傳附件的功能),確實需要返回數據來知道該功能是否執行成功呢?我的解決方法是在form 中增加一個target屬性,讓其返回的數據添加到一個隱藏的iframe的控件中,返回的數據
<label for="a"> 上傳附件 </label> <form id="uploadForm" enctype="multipart/form-data" target="frameFile" method="post"> <input type="file" id="a" name="a" onchange="fileUpload()" style="position:absolute;top:0px;right:0px;cursor:pointer; opacity:0;filter:alpha(opacity:0);z-index:999;" /> </form> <iframe id='frameFile' name='frameFile' style="display:none"> </iframe>
以下是返回頁面中后台返回數據的處理
<script type="text/javascript"> try { var data = eval("($result)") if (data.success) { alert(data.res) } window.top.LoadByFrame(data.success); } catch (e) { window.top.closeBg(); } </script>
function fileUpload() { var form = document.getElementById('uploadForm'); form.action="XXX.do?"; form.submit(); }
這樣就能夠在隱藏的iframe中顯示處理過的數據了