处理数据的三种方式
text :
xmlhttp.responseText
xml: xmlhttp.responseXML
json: javascript的原生对象,通过eval函数转换,eval("("+xmlhttp.responseText+")")
ajax.html
<form method="get"> <input type="text" name="name" id="name" onchange="checkUserAjax();"/> <br/> <div id="msg"></div> <input type="text" name="age" id="age" /><br /> </form>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String name = request.getParameter("name"); System.out.println("xxx " + name); String msg = "success"; if("admin".equals(name)){ msg = "fail"; } out.print(msg); %>
ajax.js
function $(id){ return document.getElementById(id); } function createXHR(){ var xmlhttp = null; if (window.XMLHttpRequest){ // code for IE7+,Firefox,Chrome,Opera,Safari xmlhttp=new XMLHttpRequest(); }else{ // code for IE6,IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } function checkUserAjax(){ // 1 var name = $("name").value; var xmlhttp = createXHR(); //2 xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ var str = xmlhttp.responseText; $("msg").innerHTML = str; //$("statuMsg").innerHTML=xmlhttp.responseText; if(str=="fail"){ $("name").focus(); } } } xmlhttp.open("GET","check.jsp?name="+name,true); xmlhttp.send(); //alert(xmlhttp.responseText); }