js方式利用Ajax技術從後臺獲得資料
不使用Jquery等js類庫,使用js方式建立xmlHttpRequest物件,關鍵是需要判斷瀏覽器是否支援Ajax技術,然後向伺服器提交請求,處理伺服器返回的資料。
程式碼如下:
<script type="text/javascript">
var xmlHttp=getAjaxHttp();
window.onload = function () {
xmlHttp.open( "GET", "MyLianqinAction?userid=20150001", true );
xmlHttp.onreadystatechange = updateList;
xmlHttp.send( null );
};
//Ajax回撥函式
function updateList(){
if( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
var data=xmlHttp.responseText; //獲得從伺服器返回的資料
//對資料進行處理,顯示到頁面
document.getElementById("showdata").value=data;
}
}
//建立ajax物件
function getAjaxHttp() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的瀏覽器不支援AJAX!");
return false;
}
}
}
return xmlHttp;
}
</script>