xmlhttprequest对象已经创建好了!
xmlHttp.onreadystatechange=callBack;
xmlHttp.open("POST","AjaxXML",true);
xmlHttp.send("username='"+name+"'");
这个是callback方法
function callBack()
{
alert(xmlHttp.readyState);
// 接受服务器端返回的数据
// readyState的值等于4是表示对象与服务器端交互成功的
if(xmlHttp.readyState == 4)
{ //status的值等于200,表示http与服务器交互成功
if(xmlHttp.status== 200)
{
//获取服务器端返回的数据
var domobj=xmlHttp.responseXML;
var message=domobj.getElementsByTagName("message");
if(message.length>0)
var text=message[0];
else
document.getElementById("result").innerHTML=xmlHttp.responseText;;
}
}
}
问题补充 2010-09-07 14:45
这个js访问的是一个servlet,代码如下:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by IntelliJ IDEA.
* User: alvin
* Date: 2010-9-6
* Time: 20:02:54
* To change this template use File | Settings | File Templates.
*/
public class AjaxXMLServer extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gbk");
//修改点1---把Content-type改成text/xml (必须的)
response.setContentType("text/xml;charset=gb18030");
String name=request.getParameter("username");
System.out.println(name);
try{
PrintWriter out=response.getWriter();
StringBuilder builder=new StringBuilder();
builder.append("<message>");
if(name==null||name.length()==0)
{ builder.append("您输入的用户名为空,请查证后输入!").append("</message>");
// out.print("<script>location.href='index.jsp'</script>");
}else{
if(name.equals("mengxi"))
{
builder.append("您输入的用户名存在,请重新输入!").append("</message>");
// out.print("<a href='index.jsp'>返回</a>");
}else
{ builder.append("您输入的用户名不存在,恭喜你可以使用!").append("</message>");
// out.print("<script>alert('您输入的用户名不存在,该用户名可以使用!');</script>");
// out.print("<script>location.href='index.jsp'</script>");
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
{ try{
doPost(request, response);
}catch(Exception e)
{
e.printStackTrace();
}
}
}