ajax ----简单的使用

我们学习ajax只需要4步

  1. 得到XMLHttpRequest对象

不同的浏览器支持的获取方式也不一样

  • 大多数:var xmlHttp = new XMLHttpRequest();
  • IE6.0: var xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
  • IE5以及更早的IE:var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);

既然是这样的,我们就像需要编写一个创建XMLHttpRequest对象的类

  1. 打开与服务器的链接
    xmlHppt.open() 打开以服务器的链接
    它需要三个参数:
    第一个参数: “GET” 或 “POST”
    第二个参数:“服务器资源路径”
    第三个参数 :“true” 表示异步请求、“false” 表示同步请求

  2. 发送请求
    xmlHttp.send(null) 必须给个参数,如果不给,可能会造成部分浏览器无法发送
    这里的参数实际上就是请求体

  3. 在xmlHttp上面注册一个监听器(onreadystatechange)
    xmlHttp 一个有5个状态
    0 :刚创建,该没有当调用open() 方法
    1: 调用了open() 方法 ,但是还没有调用send() 方法
    2: send() 方法已经执行完毕
    3: 服务器开始响应,但是响应并未结束
    4: 服务器响应结束 (这个使我们最常使用的)
    得到xmlHttp的状态 var state = xmlHttp.readyState
    得到服务器的响应码 var status =xmlHttp.status
    得到服务器的响应内容 (response,getWrite().print(“hello,world”))
    var content = xmlHttp.responseText 响应文本(常用)
    var content = xmlHttp.responseXML

  4. 在发送post请求的时候我们需要除了需要完成4中的内容分外,还需要都操作一步
    设置Content-Type请求头
    xmlHttp.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”)
    设置请求体
    xmlHttp.send(“name = 张三&passwd=123”)

非规范代码演示:

//获取到XMLHttpRequest对象的函数
function createXMLHttpRequest(){
	try{
		return new XMLHttpRequest();
	}catch(e){
		try{
			return new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				alert("哥们你这个浏览太牛了");
				throw e;
			}
		}
	}
}

//需要绑定响应事件(此处我未绑定,详情请看下面的“实操演练”)
//get请求
var xmlHttp = createXMLHttpRequest();  //创建XMLHttpRequest对象
xmlHttp.open("get","服务器资源路径",true);   //打开与服务器的链接
xmlHttp.send(null);  //发送请求

//------------------------------------------------------------

//需要绑定响应事件(此处我为绑定,详情请看下面的“实操演练”)
//post请求
var xmlHttp = createXMLHttpRequest();  //创建XMLHttpRequest对象
xmlHttp.open("get","服务器资源路径",true);   //打开与服务器的链接
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //设置请求头
xmlHttp.send("name = 张三&passwd=123");  //设置请求体,并发送请

//-----------------------------------------------------

//get / post 请求通用的方法
xmlHttp.onreadystatechange = function(){  //状态监听器
	//当服务器响应完成且响应状态是200是,执行if体中的语句
	if(xmlHttp.readyState = 4 && xmlHttp.status = 200){
	var content = xmlHttp.responseText;
	......
	}
}


实操演练:
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>
window.onload = function(){
	
	//获取XMLHttpRequest对象的函数
	function createXMLHttpRequest(){
		try{
			return new XMLHttpRequest();
		}catch(e){
			try{
				return new ActiveXObject("Msxml2.XMLHTTP");
			}catch(e){
				try{
					return new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){
					alert("哥们你这个浏览太牛了");
					throw e;
				}
			}
		}
	}
	
	/*  ========ajax的get方法的异步请求=========  */
	var get = document.getElementById("g");
	get.onclick = function(){
		//获取XMLHttpRequest的对象
		var xmlHttp = createXMLHttpRequest();
		//打开与服务器的连接
		xmlHttp.open("get","/ajaxIntro/Ajax1Servlet",true);
		xmlHttp.send(null); //发送请求
		xmlHttp.onreadystatechange = function(){
			if(xmlHttp.readyState==4 && xmlHttp.status == 200){
				var content = xmlHttp.responseText;
				var sp1 = document.getElementById("sp1");
				sp1.innerHTML = content;
			}
		}
	}
	
	/* =========ajax的post方法的异步请求   */
	var post = document.getElementById("p");
	post.onclick = function(){
		//获取XMLHttpRequest的对象
		var xmlHttp = createXMLHttpRequest();
		//打开与服务器的连接
		xmlHttp.open("post","/ajaxIntro/Ajax1Servlet",true);
		//设置请求头
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
		//发送请求
		xmlHttp.send("name=张三&passwd=123")
		xmlHttp.onreadystatechange = function(){
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var content = xmlHttp.responseText;
				var sp2 = document.getElementById("sp2");
				sp2.innerHTML = content;
			}
		}
	}
}
</script>
</head>
<body>
<h1>ajax的Get异步请求</h1>
<button id="g">点击我</button><br>
<h2><span id = "sp1"></span></h2>

<br><br><br>

<h1>ajax的Post异步请求</h1>
<button id="p">点击我</button><br>
<h2><span id = "sp2"></span></h2>
<br><br><br>
</body>
</html>

servlet:

package sdpei.hxh.ajax_test1;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Ajax1Servlet
 */
@WebServlet("/Ajax1Servlet")
public class Ajax1Servlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		System.out.println(1111111);
		response.getWriter().print("恭喜你,实现了ajax的get异步请求");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name = request.getParameter("name");
		String passwd = request.getParameter("passwd");
		System.out.println(2222222);
		response.getWriter().print("恭喜,姓名为:"+name+",密码是:"+passwd+"的用户,实现了ajax的post异步请求");
	}

}

前端:
在这里插入图片描述
点击按钮后:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值