处理请求页
<%
ResultSet rs = conn.executeQuery("select name from tb_book order by id desc");
String str = "";
str = "{ \"info\":\"";
if(rs.next()){
do{
str += ""+rs.getString(1)+"";
}while(rs.next());
}else{
str += "暂无图书信息";
}
str += "\" }";
out.clear(); // 清除前面的html标签
out.print(str);
out.close(); // 清除后面的html标签
%>
发起请求页:
<script>
window.onload=function(){
new AjaxRequest({
url:"getInfo.jsp?nocache="+new Date().getTime(),
type:"GET",
dataType:‘json‘,
success:function(data){
document.getElementById("showInfo").innerHTML = data.info;
},
error:function(err){
document.getElementById("showInfo").innerHTML = err.status + ":" + err.statusText;
}
});
}
</script>
<div id="showInfo"></div>
自定义封闭ajax脚本函数:
var AjaxRequest = function(obj){
this.req = new XMLHttpRequest();
this.req.open(obj.type,obj.url,true);
if(obj.type=="POST"){
this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
this.req.send();
this.req.onreadystatechange = function(){
if(this.req.readyState==4){
if(this.req.status==200){
if(obj.dataType==‘json‘){
obj.success(JSON.parse(this.req.responseText));
}else{
obj.success(this.req.responseText);
}
}else{
obj.error({status:this.req.status,statusText:this.req.statusText});
}
}
}.bind(this);
}
原文地址:http://blog.51cto.com/maplebb/2296163
时间: 2024-11-05 00:42:10