ajax初識
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script type="text/javascript">
window.onload = function() {
//1:獲取a節點,並對其添加onclick()相應函數
document.getElementsByTagName("a")[0].onclick = function() {
// 2:創建一個XMLHttpRequest對象
var request = new XMLHttpRequest();
// 3:準備發送請求的數據:url
var url = this.href;
//4:調用XMLHttpRequest對象的open方法
request.open("GET", url);
//5:調用XMLHttpRequest對象的send方法
request.send(null);
//6:為XMLHttpRequest對象添加Onreadystatechange響應函數
request.onreadystatechange = function() {
//判斷響應是否完成:XMLHttpRequest的readyState的屬性值為4的時候
// alert(request.readyState);
if(request.readyState == 4) {
// 判斷響應是否可用,XMLHttpRequest的status的屬性值為200的時候
if(request.status == 200 || request == 304){
//8:打印響應結果
alert(request.responseText);
}
}
}
return false; //保證不會調轉啊,取消點擊的默認行為
};
}
</script>
</head>
<body>
<a href="helloAjax.txt">helloAjax</a>
</body>
</html>
上述實現默認a鏈接不跳轉,get方法讀取hello_world.txt內部內容
*POST:加 request.setRequestHeader("ContentType","application/x-www-form-urlencoded");
ajax初識