Ajax
- index.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">
window.οnlοad=function(){
var btn=document.getElementById("btn");
btn.οnclick=function(){
//如何发送ajax请求,异步请求
//异步通信,通信之间没有任何优先级关系
//同步通信,上一次通信完成,下一次才可以继续
//在代码中
//如果发的是异步请求,那么发送请求后,后面的代码,不用等待请求完成再执行
//如果发的是同步请求,那么发送请求后,后面的代码,需要等待请求完成再执行
//1.创建xhr对象,用这个对象来向服务器发送请求
var xhr=new XMLHttpRequest();
//2.open(),send()
//method请求类型GET,POST
//url请求地址
//async是否为一部,默认是true
//3.open()方法知识设置请求信息的,可以将请求参数呆在url上
xhr.open("GET","AJAXServlet?username=abc&pwd=123", true);
//4.send(body) body:请求体,把要发送的数据放在请求体
//5.调用send()方法将
xhr.send();
//6.必须接收响应
//xhr对象有两个属性
//responseText 获得字符串形式的响应数据
//responseXML 获得XML形式的响应数据
//必须在响应完成后完成接收,必须监控请求对象的状态
//onreadystatechange 每当请求状态改变时就会执行
//xhr对象有一个readyState
//0:请求未初始化
//1:服务器连接已建立
//2:请求已接收
//3:请求处理中
//4:请求已完成,且响应已就绪
xhr.onreadystatechange=function(){
//alert(xhr.readyState);
//当请求已完成的时候
if(xhr.readyState==4&&xhr.status==200){
//获取xhr的数据
alert(xhr.responseText);
var divEle=document.getElementById("div_time");
divEle.innerHTML=xhr.responseText;
}
};
}
}
</script>
</head>
<body>
<iframe name="ajaxframe"></iframe>
<a href="AJAXServlet" target="ajaxframe">发送请求,获取服务器时间</a>
<button id="btn">发送ajax请求</button>
<div id="div_time"></div>
</body>
</html>
- AJAXServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("收到请求了");
Date date=new Date();
String format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
response.getWriter().write(format);
}
- 兼容问题
- jquery发get请求
<script type="text/javascript">
$(function(){
$("#btn2").click(function(){
//jQuery.get(url,[data],[callback],[type])
//jquery如何接收参数,只需要在回掉函数里面定义一个接收响应数据的参数
//data表示传入的数据,也可以夹在url后面
//callback表示回调函数
//type表示响应的数据是什么类型:xml,html,script,json,text,_default
$.get("AJAXServlet?username=abc&pwd=123",function(data){
alert(data);
},"text");
});
});
</script>
me=abc&pwd=123",function(data){
alert(data);
},“text”);
});
});