天天看點

原生态ajax請求怎麼寫

//第一步:建立XMLHttpRequest對象

var xmlhttp;

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp = new XMLHttpRequest();

}

else {// code for IE6, IE5

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

//第二步:設定回調函數

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

}

//第三步:打開連接配接

xmlhttp.open("GET","test1.txt",true);

//第四步:發送請求

//post請求的時候,需要設定requestHearder屬性。兩個參數,第一個參數表示頭名稱,第二個表示頭的值

//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

//然後再send中傳入請求的參數。如:"fname=Bill&lname=Gates"

xmlhttp.send();

繼續閱讀