通过传统的JavaScript的ajax的方式从服务器端取回一个“Hello Ajax!”的字符串并显示在页面上。
原始页面:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>原生JavaScript实现ajax</title>
</head>
<body>
<input type="button" value="Ajax提交" onclick="ajax()" />
<div id="resTest"></div>
<script>
function Ajax(){
var xmlHttpReq = null;
if(window.ActiveXObject){ // ie5 ie6是以ActiveXObject的方式引入XMLHTTPRequest对象的
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){ // 除ie5 ie6以外的浏览器
xmlHttpReq = new XMLHttpRequest(); // 实例化一个XMLHttpRequest对象
}
// 使用open()方法初始化XMLHttpRequest对象,指定http方法以及URL,加true表示使用异步方式
xmlHttpReq.open("GET","test.php",true);
// 当readyState值被改变时,会激发一个readystatechange事件,可以使用onreadystatechange属性来注册该回调事件处理器
xmlHttpReq.onreadystatechange = RequestCallBack;
// 使用send()方法发送该请求,因为这个请求使用的是http的get方式,所以可以在不指定参数或使用null参数的情况下调用send()方法
xmlHttpReq.send(null);
// 当请求状态改变时,XMLHttpRequest对象调用onreadystatechange属性注册的事件处理器,因此,在处理该响应之前,事件处理器应该首先检查readyState的值和
// http状态。当请求完成加载(readyState的值为4)并且响应已经成功(Http状态值为200)时,就可以调用有个JavaScript函数来处理该响应内容,如下:
function RequestCallBack(){ // 一旦readyState值改变,就会调用该函数
if(xmlHttpReq.readyState == 4){
if(xmlHttpReq.status == 200){
document.getElementById("resTest").innerHTML = xmlHttpReq.responseText;
}
}
}
}
</script>
</body>
</html>
点击按钮后的样子(当然,我没搭后端web,这是我伪造的,hhhh,重在理解原生JavaScript的ajax的实现过程):

网友评论