form上傳檔案並獲取返回值
阿新 • • 發佈:2019-01-05
原理:頁面寫一個隱藏的iframe,form的target指向這個iframe,在iframe的load事件中獲取返回結果。
<!-- 上傳 --> <form action="" method="post" enctype="multipart/form-data" target="hidden_frame" onsubmit="$('body').mask('正在上傳,請稍後...');"> <input type="submit" value="上 傳" /> </form> <iframe id="hidden_frame" name='hidden_frame' style='display: none'></iframe>
//獲取匯入返回值
function initIframe(){
$('#hidden_frame').load(function(){ //新增iframe的onload事件
$("body").unmask();
var resText = $(this).contents().find("body").find('pre').text(),
res = JSON.parse(resText); //獲取返回結果
if(res){
//根據返回結果, 執行的操作
}
});
}
initIframe();
<!-- 匯出 --> <form action="" method="post" target="_blank"> <input type="submit" value="導 出" /> </form>
//get請求匯出
window.location.href = encodeURI(url); //當前視窗開啟
window.open(url); //新視窗開啟