解決Ajax返回數據包含整個jsp頁面的問題
阿新 • • 發佈:2018-10-09
inner time() jsp頁面 .get bin from time header ror 處理請求頁
<% 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); }
解決Ajax返回數據包含整個jsp頁面的問題