重点:理解Ajax原理,几大步骤:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'ajax.jsp' starting page</title> <Meta http-equiv="pragma" content="no-cache"> <Meta http-equiv="cache-control" content="no-cache"> <Meta http-equiv="expires" content="0"> <Meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <Meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function createXHR(){ //创建XMLHttpRequest对象 try{ //alert(1); return new ActiveXObject('Msxml2.xmlhttp'); }catch(e){ //alert(2); return new XMLHttpRequest(); } } //createXHR() function checkuserexist(){ var username=document.getElementById('userform').username.value; //alert(username); var xhr=createXHR(); xhr.onreadystatechange=function(){ //注册处理函数 if(xhr.readyState==4){ // 服务器响应正确(当服务器响应正确时,返回值为200的状态码) if (xhr.status == 200) { var msg=xhr.responseText; //处理响应 document.getElementById('usermsg').innerHTML='<span style="color:reg">'+msg+'<span>' } } } //建立连接 xhr.open('GET','index.jsp?u='+username,true); //发送请求 xhr.send(null); //处理响应 // xhr.responseText; } </script> </head> <body> <form id='userform'> 请填写用户名:<input type='text' name='username',id='username' onblur='checkuserexist();'/> <div id='usermsg'></div> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; response.setCharacterEncoding("utf-8"); String name=request.getParameter("u"); if(name.equals("abc")){ out.println("存在"); }else{ out.println("不存在"); } out.println("jioijjioj"); out.flush(); %>
结果:
原文链接:https://www.f2er.com/ajax/164719.html