DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX基礎知識 >> AJAX下的請求方式以及同步異步的區別小結
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請求對象。)
復制代碼 代碼如下:
//同步傳輸模式
function RequestByGet(nProducttemp,nCountrytemp)
{
var xmlhttp
if (window.XMLHttpRequest)
{
//isIE = false;
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
//isIE = true;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Web page location.
var URL="http://www.baidu.com/;
xmlhttp.open("GET",URL, false);
//xmlhttp.SetRequestHeader("Content-Type","text/html; charset=Shift_JIS")
xmlhttp.send(null);
var result = xmlhttp.status;
//OK
if(result==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
}
xmlhttp = null;
}

//異步傳輸模式
var xmlhttp
function RequestByGet(nProducttemp,nCountrytemp)
{
if (window.XMLHttpRequest)
{
//isIE = false;
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
//isIE = true;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Web page location.
var URL="http://www.baidu.com/";
xmlhttp.open("GET",URL, true);
xmlhttp.onreadystatechange = handleResponse;
//xmlhttp.SetRequestHeader("Content-Type","text/html; charset=UTF-8")
xmlhttp.send(null);
}
function handleResponse()
{
if(xmlhttp.readyState == 4 && xmlhttp.status==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
xmlhttp = null;
}
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved