使用原生的javascript代码来实现ajax操作,可以看做ajax的入门
代码如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>ajax的测试页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
//1.使用原生的javascript来实现ajax操作
window.onload = function(){
//2.获取a节点,并且为其添加onclick响应事件
document.getElementById("ajax").onclick = function(){
//3.创建XMLHttpRequest对象
var request = new XMLHttpRequest();
//4.准备发送的数据
var url = this.href;
var method = "GET";
//5.调用XMLHttpRequest的open()方法
request.open(method,url);
//6.调用XMLHttpRequest的send()方法
request.send(null);
//7.为XMLHttpRequest对象添加onreadystatechange响应函数
request.onreadystatechange = function(){
//8.判断响应是否完成,XMLHttpRequest对象的readyState属性值为4的时候
if(request.readyState == 4){
//9.在判断响应是否可用,XMLHttpRequest对象的status属性值为200
if(request.status == 200 || request.status == 304){
//10.打印响应结果,responseText
alert(request.responseText);
}
}
}
//11.取消超链接的默认行为
return false;
}
}
</script>
</head>
<body>
<a href="ajax/ajax.txt" id = "ajax">helloAjax</a>
</body>
</html>
结果如下: