现在的位置: 首页 > 综合 > 正文

ajax in jsp sample

2013年10月01日 ⁄ 综合 ⁄ 共 2591字 ⁄ 字号 评论关闭

/**************************************************

function:ajax in jsp sample

tools:eclipse+jboss

test tools:firefox,ie,360

author:chinayaosir 

QQ:44633197  QQ Group:8284865,34610648
blog http://blog.csdn.net/chinayaosir

 

context list:

main jsp:helloworld.jsp

call jsp:sayhello.jsp

------------------------------------------

run value:

hello ajax with jsp!
ip address= x.xxx.x.x

date time =MM/dd/yyyy hh:mm:ss

 

**************************************************/

-------------helloworld.jsp-------------------------------

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello Ajax World</title>
<script type="text/javascript">
//bind js function into button event
window.onload = function (){
 document.getElementById('btn_say').onclick = sayhello;
 document.getElementById('btn_clr').onclick = sayclear;
};

function sendRequest(){
     var xhr = createXHR();    
     if (xhr){
      xhr.open("GET","sayhello.jsp",true);
      xhr.onreadystatechange = function(){handleResponse(xhr);};
      xhr.send(null);
     }
}

function createXHR(){
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}  
   try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
 
   alert("XMLHttpRequest not supported");  
   return null;
}

function handleResponse(xhr){
  if (xhr.readyState == 4  && xhr.status == 200){
 xmlDoc=xhr.responseText;
   var multirow = xmlDoc.split("&&");
   var singrow;
   var showstring="";
   for(var i=0;i<multirow.length-1;i++){
        singrow= multirow[i];
  showstring+=singrow;
    }
    var responseOutput= document.getElementById("responseOutput");
    responseOutput.innerHTML=showstring;
    }
}
function sayhello(){
 sendRequest();
}
function sayclear(){
  var responseOutput= document.getElementById("responseOutput");
  responseOutput.innerHTML="";
}

</script>
</head>
<body>
<form action="#">
 <input type="button" value="sayhello" id="btn_say" />
  <input type="button" value="sayclear" id="btn_clr" />
</form>
<br />
<div id="responseOutput">&nbsp;</div>
</body>
</html>

 

 

*************************************************************

-------------sayhello.jsp-------------------------------

<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setContentType("text/xml");
String showstring="";
showstring+="hello ajax with jsp!<br>";
showstring+="ip address= "+request.getRemoteAddr()+"<br>";
showstring+="date time ="+new java.text.SimpleDateFormat("MM/dd/yyyy hh:mm:ss").format(new java.util.Date())+"<br>&&";
response.getWriter().write(showstring);
%>

 

 

抱歉!评论已关闭.