ajax中的同步异步
生活随笔
收集整理的這篇文章主要介紹了
ajax中的同步异步
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
請求方式,分為GET與POST: GET 最為常見的HTTP請求,普通上網瀏覽頁面就是GET。GET方式的參數請求直接跟在URL后,以問號開始。(JS中用window.location.search獲得)。參數可以用encodeURIComponent進行編碼,使用方式:
| var?EnParam?=?encodeURIComponent(param); |
URL只支持大約2K的長度,即2048字符數;使用GET進行AJAX請求時候會緩存導致出現的頁面不是正確的,一般方法加random參數值;ajax.send(null)。
POST
向服務器提交數據用到。
需要將form表單中的值先取出轉換成字符串,用&符號連接,(同GET傳參數一樣);提交數據量2GB ;使用ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'),處理提交的字符串;ajax.send(strings),這個strings表示form中需要提交的內容,例如a=1&b=2類似這樣的字符串。
?
同步與異步:
ajax.open方法中,第3個參數是設同步或者異步。prototype等js類庫一般都默認為異步,即設為true。先說下同步的情況下,js會等待請求返回,獲取status。不需要onreadystatechange事件處理函數。而異步則需要onreadystatechange事件處理,且值為4再正確處理下面的內容。
(注:文中的 ajax 表示XMLHTTP請求對象。)
1 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 //同步傳輸模式 2 3 function RequestByGet(nProducttemp,nCountrytemp) 4 { 5 var xmlhttp 6 7 if (window.XMLHttpRequest) 8 { 9 //isIE = false; 10 xmlhttp = new XMLHttpRequest(); 11 } 12 else if (window.ActiveXObject) 13 { 14 //isIE = true; 15 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 16 } 17 18 //Web page location. 19 var URL="http://www.baidu.com/; 20 xmlhttp.open("GET",URL, false); 21 //xmlhttp.SetRequestHeader("Content-Type","text/html; charset=Shift_JIS") 22 xmlhttp.send(null); 23 var result = xmlhttp.status; 24 25 //OK 26 if(result==200) 27 { 28 document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText; 29 } 30 xmlhttp = null; 31 } 32 33 34 //異步傳輸模式 35 var xmlhttp 36 37 function RequestByGet(nProducttemp,nCountrytemp) 38 { 39 if (window.XMLHttpRequest) 40 { 41 //isIE = false; 42 xmlhttp = new XMLHttpRequest(); 43 } 44 else if (window.ActiveXObject) 45 { 46 //isIE = true; 47 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 48 } 49 50 //Web page location. 51 var URL="http://www.baidu.com/"; 52 xmlhttp.open("GET",URL, true); 53 xmlhttp.onreadystatechange = handleResponse; 54 //xmlhttp.SetRequestHeader("Content-Type","text/html; charset=UTF-8") 55 xmlhttp.send(null); 56 } 57 58 function handleResponse() 59 { 60 if(xmlhttp.readyState == 4 && xmlhttp.status==200) 61 { 62 document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText; 63 xmlhttp = null; 64 } 65 }?
轉載于:https://www.cnblogs.com/huanghundaxia/p/5698356.html
總結
以上是生活随笔為你收集整理的ajax中的同步异步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ionic@2.0 beta版本安装指南
- 下一篇: sql基线建立-知识准备