ajax
1.根据不同浏览器获得异步对象var xmlHttp=new XMLHttpRequest()
或者newActvieXObject("Msxml12.XMLHTTP") newActvieXObject("Miscrosoft.XMLHTTP")
2.打开链接open("post","url",true)
3. 如果是post方式要设置请求头setRequestHeader("Content-Type","application/x-www-form-urlencoded")
get方式不需要设置
4. 发送请求:1.getsend(null)
2.postsend("username=xxx&&password=yyy")
5.检查异步对象的onreadystatechange
事件注册监听器,当xmlHttp.readyState==4&&xmlHttp.status==200
时,xmlHttp.responseText
获取服务器的响应的文本.xmlHttp.responseXML
获取 服务响应的xml文件,返回一个document,同时服务器端需要改响应编码response.response.setContentType("text/xml;charset=utf-8");
例1:登陆验证
<script>
function createXMLHttpRequest(){
try {
return new XMLHttpRequest();
} catch (e) {
try {
return new ActvieXObject("Msxml12.XMLHTTP");
} catch (e) {
try {
return new ActvieXObject("Miscrosoft.XMLHTTP");
} catch (e) {
alert("你得浏览器不支持");
throw e;
}
}
}
}
window.onload=function(){
var name=document.getElementById("na1");
name.onblur=function(){
var xmlHttp=createXMLHttpRequest();
xmlHttp.open("POST","<c:url value='/LoginServlet'/>",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("username="+name.value);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var text=xmlHttp.responseText;
var msg=document.getElementById("m");
if(text=="1"){
msg.setAttribute("color", "red");
msg.innerHTML="用户名已经注册";
}else if(text=="2"){
msg.setAttribute("color", "green");
msg.innerHTML="用户名可以注册";
}else if(text=="3"){
msg.setAttribute("color", "red");
msg.innerHTML="用户名不能为空";
}
}
};
};
};
</script>
</head>
<body>
<form action="<c:url value='/LoginServlet'/>" method="post">
用户名:<input type="text" id="na1" name="username" value=""><font id="m"></font><br>
密 码:<input type="text" name="password" value=""><br>
<input type="submit">
</form>
</body>
</html>
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username=request.getParameter("username");
if(username==null||username.trim().isEmpty()){
response.getWriter().print("3");
}
else if(username.equals("孙超")){
response.getWriter().print("1");
}else{
response.getWriter().print("2");
}
}
}