function fun() {
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. 建立连接
xmlhttp.open("POST","ajaxServlet?username=tom",false);// 同步或异步请求:true(异步)或 false(同步)
//3.发送请求
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
//当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
xmlhttp.onreadystatechange=function()
{
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//获取服务器的响应结果
var responseText = xmlhttp.responseText;
alert(responseText);//为什么原生js同步请求(false)拿不到响应的数据
}
}
}
---------------------***********Servlet************-------------------------------------------
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String username = request.getParameter("username");
//模拟处理业务逻辑的耗时
Thread thread = new Thread();
try {
thread.sleep(3000);//让线程睡3秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(username);
//响应
response.getWriter().write("hello:"+username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
断点看看有没有进来
response.getWriter().write("hello:"+username);
有响应的数据
username : "tom response={ResponseFacade@3378}
因为不会打前端的断点.......只能通过F12
Status Code: 200
xmlhttp.readyState不知道是几
@一切至于创新: 浏览器的控制台中打断点哦,百度学一下,开发必备的技能