robot
最新文章(10)
Mqskit 和其它相關工具
CPython 的 GC 二、三事
寫 Mecurial Extension 是件快樂的事!
Mozilla 台灣辨公室徵人啟事
關於 Apple 的兩項專利
core dump 之前的 frame
怎麼發出 beep 聲?
先承認你要找的是奴才吧!
程式碼要清的多乾淨?
FreeBSD 的 Thread-Local Storage 實作
首頁
新編
最新留言
Entries RSS
重要關鍵字(10)
coding (122)
Python (93)
FreeBSD (71)
WEB (61)
URL (48)
hardware (46)
javascript (36)
Linux (34)
blog (30)
C++ (16)
所有關鍵字
新增 URL
AJAX 如何傳送資料到不同 host?
by thinker
2 Columns
關鍵字:
WEB
javascript
coding
$AJAX$ 通常使用 HttpRequest , 非同步 (aynchronize) 傳送資料到遠端。但 HttpRequest 有 host 的限制,只能和目前 document 的來源 host 溝通。於是,為了傳送資料到不同的 host,可透過隱藏 (hidden) 的 frame 或 iframe,將資料編碼成 $URL$ 的一部分,傳送到其它 server,以達到溝通的效果。 但是,大部分 browser 對 $URL$ 長度都有大小不一的限制。IE 則限制在 2048 bytes 的最大長度,否則會造成錯誤。因此,要傳送大量資料時,只好透過 form,以 post method 傳送。但 form 會造成網頁換頁,無法達到 asynchronize 的要求。 這裡介紹的方法是,將 form 的 target 指定為隱藏的 frame 或 iframe,如此就可以不用換頁,又可傳送大量資料。 {{{ <iframe style="visibility: hidden" name="_foo"> </iframe> <form id="target" target="_foo" enctype="application/x-www-form-urlencoded" method="POST"> ...... </form> ........... ............... <script> document.getElementById("target").submit(); </script> }}} == 補充 == tools.js {{{ function new_elm(tname) { return document.createElement(tname); } function get_body() { return document.getElementsByTagName("body").item(0); } function px(v) { return "" + v + "px"; } var safe_request_wait_for_clean = new Array(); function safe_request(url, data, onload_callback) { var div; var form, frame, o; var body = get_body(); var full_loaded, clear, myclear; var tg = "__SR_" + (new Date()).UTC; while(safe_request_wait_for_clean.length > 0) { clear = safe_request_wait_for_clean.pop(); clear(); } div = new_elm("div"); div.style.visibility = "hidden"; div.style.width = px(0); div.style.height = px(0); div.style.position = "absolute"; div.style.top = px(-1000); div.style.left = px(-1000); form = new_elm("form"); form.action = url; form.enctype = "application/x-www-form-urlencoded"; form.method = "POST"; form.target = tg; o = new_elm("input"); o.setAttribute("type", "hidden"); o.setAttribute("name", "data"); o.value = data; form.appendChild(o); frame = new_elm("iframe"); frame.setAttribute("name", tg); frame.style.visibility = "hidden"; frame.style.width = px(0); frame.style.height = px(0); myclear = function() { body.removeChild(div); } full_loaded = function(evt) { if(onload_callback != null) onload_callback(evt); safe_request_wait_for_clean.push(myclear); } frame.addEventListener("load", full_loaded, false); div.appendChild(form); div.appendChild(frame); body.appendChild(div); form.submit(); } }}} HTML file {{{ <html> <script type="text/ecmascript" src="tools.js"> </script> <script> function work() { safe_request("http://url/to/somewhere", "somedata", null); } </script> <body> Hello<p> <input type="button" onclick="$javascript$:work()" value="work"> <p> hello </body> </html> }}}
最後更新時間: 2006-10-18 11:33:00 CST |
引用
查詢:
COMMENTS: