本文的实现是通过按钮点击,获取服务器页面的随机数
模拟服务器的页面
randNum.jsp
<%@ page contentType="text/html; charset=GBK" language="java" %>
<%
out.println(Math.round(Math.random()*10));
%>
Html页面的代码,利用jQuery方式,要导入jQuery.min.js库
<body>
<input type="button" value="获取" onclick="getPrice()" />
<div id="resultDiv" ></div>
<script type="text/javascript" >
var xmlHttpReq;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
xmlHttpReq=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){ }
}
}
}
function getPrice(){
createXMLHttpRequest();
var uri="randNum.jsp";
xmlHttpReq.open("POST",uri,true);
xmlHttpReq.onreadystatechange=processResponse;
xmlHttpReq.send(null);
}
function processResponse(){
if(xmlHttpReq.readyState==4){
if(xmlHttpReq.status==200){
document.getElementById('resultDiv').innerHTML=xmlHttpReq.responseText;
}else{
window.alert('请求页面异常');
}
}
}
</script>
</body>
1、首先创建XMLHttpRequest,并判断当前的浏览器是否支持XMLHttpRequest,IE5/ IE6不支持XMLHttpRequest
2、通过open方法打开与uri服务器地址的连接,并且采用post的参数方式,允许异步传输
3、指定XMLHttpRequest状态发生改变的指定执行的函数processResponse
4、在执行processResponse函数时,判断服务器的响应是否完成,只需判断XMLHttpRequest对象的readyState==4属性即可;服务器响应完成后,还应该判断服务器响应是否正确,XMLHttpRequest对象的status==200属性进行。
5、服务器响应正确就获取回应文本responseText
6、使用send方法发送请求
** 利用protytypeJS的Ajax方式获取ResponseText,要求导入prototype.js库
<body>
<input type="button" value="获取" onclick="getPrice()" />
<div id="resultDiv" ></div>
<script type="text/javascript">
function getPrice(){
var uri="randNum.jsp";
new Ajax.Request(
uri,
{
method:"post",
parameters:null,
onComplete:showResponse,
asynchronous:true
});
}
function showResponse(request){
$('resultDiv').innerHTML=request.responseText;
}
</script>
</body>
无须创建XMLHttpRequest对象,只创建Ajax.Request()对象就可以完成异步请求发送
Ajax.Request( url, options) 格式,options部分参数如下:
asynchronous 是否异步发送请求
method 发送请求的方式
parameters 请求参数,应采用name1=value1&name2=value2形式
onCreate 当Ajax.Request对象初始化完成后触发该属性指定的回调函数
onComplete 请求交互完成后触发器函数
==============
初步学习Ajax,以此记录