var
xmlhttp;
if(window.XMLHttpRequest==XMLHttpRequest)
{
xmlhttp=new
XMLHttpRequest();
}else{
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4
&& xmlhttp.status==200)
{
//回調函數,在此可以將後臺傳遞的值,顯示頁面
}
};
xmlhttp.open("POST",
"url", true);//url 爲要跳轉的頁面
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");//post請求設置參數時使用
xmlhttp.send("optionValue=12");設置要傳遞的參數
GET請求:
var
xmlhttp;
if(window.XMLHttpRequest==XMLHttpRequest)
{
xmlhttp=new
XMLHttpRequest();
}else{
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4
&& xmlhttp.status==200)
{
//回調函數,在此可以將後臺傳遞的值,顯示頁面
}
};
//url
爲要跳轉的頁面 傳遞參數demo_get2.asp?fname=Bill&lname=Gates
xmlhttp.open("GET",
"url", true);
xmlhttp.send();設置要傳遞的參數
GET 還是 POST?
與 POST 相比,GET 更簡單也更快,並且在大部分情況下都能用。
然而,在以下情況中,請使用 POST 請求:
- 無法使用緩存文件(更新服務器上的文件或數據庫)
- 向服務器發送大量數據(POST 沒有數據量限制)
- 發送包含未知字符的用戶輸入時,POST 比 GET 更穩定也更可靠
異步 - True 或 False?
AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 對象如果要用於 AJAX 的話,其 open() 方法的 async 參數必須設置爲 true:
xmlhttp.open("GET","ajax_test.asp",true
);