由於頁面在已經展開的某些情況下,需要通過用戶操作來調用一些當前尚未獲取的數據,這就會用到異步。
web上比較簡單的做法,是使用一個iframe來取得相應的數據,並且在iframe的父窗口上獲取iframe內頁面的數據。
這裏使用一個校驗的例子。
用戶端提供一個值,點擊一個按鈕去進行校驗。這時候已經在同一個頁面填寫了大量的信息,所以不能整個頁面跳轉。通過異步的方式,在iframe內反饋回校驗的結果,父窗口獲取結果。(注意:由於iframe內頁面數據可能需要一定的等待時間,父窗口需要監聽iframe獲取數據的狀態,這裏只做一個5秒鐘的等待,沒有真實實現監聽)
/*取得當前填寫的實物儲位號的校驗結果*/
function checkEntityArchive() {
var entityArchive = document.getElementById("i_EntityArchive");
var myaction = "/archiveKeepOnFileGetBe/";
var frm = document.createElement('form');
frm.action = myaction;
frm.method = 'post';
frm.target = 'iframeTemp';
var keyText = document.createElement('input');
keyText.type = 'hidden';
keyText.name = 'key';
keyText.value = 'Love U';
frm.appendChild(keyText);
document.body.append(frm);
frm.submit();
// entityArchive.value = window.frames["iframeTemp"].document.getElementById('checkResult').value;
// entityArchive.value = window.frames["iframeTemp"].contentWindow.document.body.innerText;
setTimeout(function () {
var iframe = document.getElementById('iframeTemp');
entityArchive.value = iframe.contentWindow.document.getElementById('checkResult').value;
// entityArchive.value = window.frames["iframeTemp"].document.getElementById('checkResult').value;
// entityArchive.value = iframe.contentWindow.document.body.innerHTML;
}, 5 * 1000);
}
<div><span class="spanStyle1">實物儲位號</span><input id="i_EntityArchive" name="i_EntityArchive" type="text"><input
id="i_EntityArchive_check" name="i_EntityArchive_check" type="button" value="檢查"
onclick="checkEntityArchive()" class="btn3">
<iframe id="iframeTemp" name="iframeTemp" style="display: none;"></iframe>
</div>
在js代碼中,我們實現了一個動態加載的form,其中 一個 name 爲 key 的 input 值爲 “Love U”,是我們提交的關鍵信息。(作爲要校驗檢查的儲位號)
如果這個儲位號存在,仍返回這個儲位號,如果不存在,就返回提示信息。
服務端golang實現如下
func ArchiveKeepOnFileGetBeHandler(writer http.ResponseWriter, request *http.Request) {
var temp = request.FormValue("key")
//log.Println(temp)
//fmt.Fprintln(writer,"Hello My Moon!",temp)
var tpl = `<html>
<head>
<title>返回實物儲位號校驗結果</title>
</head>
<body>
<input id="checkResult" name="checkResult" type="text" value="` + temp + `">
</form>
</body>
</html>
`
writer.Write([]byte(tpl))
}
golang代碼省略了具體的校驗過程,只是返回了一個頁面。不要擔心這個返回的頁面會替換web前端的用戶操作頁,在js代碼中
frm.target = 'iframeTemp';
就表示,新數據頁面會在 iframeTemp 的窗口中打開,即 iframe 窗口中。【這裏注意 iframe 窗口的 name和id】
golang中的變量 temp就是我們接收的數據,也是校驗檢查後,最終返回的數據。爲了便於父窗口獲取數據,返回值放在一個id爲 checkResult 的 input中。
前端頁面,通過一個 setTimeout 方法,等待了 5 秒鐘,然後獲取返回值。
如果你想返回其他的值,就在 golang 的函數中去隨意的設置即可。_