java ajax初始化
<script type="text/javascript">
var http_request = false;
function createXMLHttpRequest() {
if (window.ActiveXObject) { // IE浏览器
http_request = new ActiveXObject("Msxml2.XMLHTTP"); //创建XMLHttpRequest对象
}else if (window.XMLHttpRequest) { // 非IE浏览器
http_request = new XMLHttpRequest(); //创建XMLHttpRequest对象
}
if (!http_request) {
alert("不能创建XMLHttpRequest对象实例!");
return false;
}
}
function getResult() {
var responseContext; //用于存放从服务器返回的响应结果
if (http_request.readyState == 4) { // 判断请求状态
if (http_request.status == 200) { // 请求成功,开始处理返回结果
responseContext = http_request.responseText; //获取服务器的响应内容
if(responseContext.indexOf("true")!=-1){
alert("恭喜您!该用户名有效!");
}else{
alert("抱歉!该用户名已经被注册!");
}
} else { // 请求页面有错误
alert("您所请求的页面有错误!");
}
}
}
function checkUsername(username) {
if (username.value == "") {
alert("请输入用户名!");
username.focus();
return;
} else {
createXMLHttpRequest();
http_request.onreadystatechange = getResult; //调用返回结果处理函数
http_request.open("GET","CheckUser?username="+username.value, true); //创建与服务器的连接
http_request.send(null); //向服务器发送请求
}
}
</script>
例子2:
<script type="text/javascript"> var xmlHttp = false; function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0"); }else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } } function startRequest(){ createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", "http://localhost:8080/MyFirstWebPro/user.xml", false); xmlHttp.send(); } function handleStateChange(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ document.getElementById("results").innerHTML = xmlHttp.responseText; }else{ alert("您所请求的页面有错误!"); } } } </script>
<body onload="startRequest();">
<div id="results"></div>
user.xml如下
<?xml version="1.0" encoding="gb2312"?> <table> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <tr> <td>王丽丽</td> <td>22</td> <td>女</td> </tr> <tr> <td>张芳</td> <td>22</td> <td>女</td> </tr> <tr> <td>张辉</td> <td>22</td> <td>男</td> </tr> </table>