Ajax
1、AjaxAjax=Asynchronous Javascript And XML(异步的JavaScript和XML) 有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。 2、使用步骤1、检测浏览器为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject : var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+,Firefox,Chrome,Opera,Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6,IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
2、当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("msgId").innerHTML = xmlHttp.responseText;
}
}
3、GET ,POST与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。 然而,在以下情况中,请使用 POST 请求: 无法使用缓存文件(更新服务器上的文件或数据库) xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
使用POST请求: xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
注:必须加上 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
3、示例Dmeo public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html");
}
public void doPost(HttpServletRequest request,IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username=request.getParameter("username");
System.out.println("servlet收到 "+username);
String str ="";
if("abc".equals(username)){
str = "用户名已经存在";
}else{
str = "用户名可用";
}
response.getWriter().print(str);
}
}
jsp代码 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> function LoginDemo(obj) { var usernameText = obj.value; var xmlHttp = null; if (window.XMLHttpRequest) { // code for IE7+,Safari xmlHttp = new XMLHttpRequest(); } else {// code for IE6,IE5 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("msgId").innerHTML = xmlHttp.responseText; } } xmlHttp.open("POST","${pageContext.request.contextPath}/LoginServlet"); xmlHttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlHttp.send("username=" + usernameText); } </script>
</head>
<body>
<form action="">
用户名:<input type="text" name="username" onblur="LoginDemo(this)" /> <span id="msgId"></span> <br /> 密码:<input type="text" name="password" /><br />
<input type="submit" value="注册" />
</form>
</body>
</html>
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |