3.1 XMLHttpRequest对象
XMLHttpRequest是浏览器接口对象,该对象的API可被JavaScript、VBScript以及其它 web 浏览器内嵌的脚本语言调用,通过HTTP协议在浏览器和web服务器之间收发XML或其它数据。XMLHttpRequest可以与服务器实现异步交互,而无需让整个页面刷新,因此成为 Ajax编程的核心对象。
3.2 Ajax的使用步骤
1. 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
2. 给定请求方式以及请求地址
xhr.open("get","https://www.youkuaiyun.com/");
3. 发送请求
xhr.send();
4. 获取服务器端给客户端的响应数据
xhr.onreadystatechange = function(){
//0:open()没有被调用
//1:open()正在被调用
//2:send()正在被调用
//3:服务端正在返回结果
//4:请求结束,并且服务端已经结束发送数据到客户端
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("span").innerHTML=xhr.responseText;
alert(xhr.responseText); }
}
4 实例
4.1Jsp页面
$Title$function but(){
var xhr = new XMLHttpRequest();
xhr.open("get","ajax.do");
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
alert(xhr.responseText);
document.getElementById("span").innerHTML=xhr.responseText;
}
}
}
优快云
4.2 Servlet
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.println("Hello Ajax");
pw.flush();
pw.close();
}
}
4.3 运行效果
异步发送,而且还是显示原来的页面