ajax交互
1.servlet get
servlet:
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.write("hello ajax");
System.out.println("ServletDemo1执行了");
java:
<script type="text/javascript">
window.onload=function(){
document.getElementById("b1").onclick=function(){
var xhr=createXmlHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200||xhr.status==304){
var data =xhr.responseText;
alert(data);
document.getElementById("d1").innerHTML=data;
}
}
}
xhr.open("GET","/ajaxdayday28/servlet/ServletDemo1?time="+new Date().getTime());
xhr.send(null);
};
}
function createXmlHttpRequest(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
try{
xmlHttp=new ActiveXobject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp=new ActiveXobject("Microsoft.XMLHTTP");
}catch(e){}
}
}
return xmlHttp;
}
</script>
2.servlet post
servlet:
String username= request.getParameter("username");
String pwd= request.getParameter("pwd");
java:
<script type="text/javascript">
window.onload=function(){
document.getElementById("b1").onclick=function(){
var xhr=createXmlHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200||xhr.status==304){
}
}
}
xhr.open("POST","/ajaxdayday28/servlet/ServletDemo2?time="+new Date().getTime());
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username=admin&pwd=123");
};
}
function createXmlHttpRequest(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
try{
xmlHttp=new ActiveXobject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp=new ActiveXobject("Microsoft.XMLHTTP");
}catch(e){}
}
}
return xmlHttp;
}
</script>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。