js原生ajax请求代码示例

一、前端html页面编写






ajax的测试


	
用户名:
密 码:

二、原生ajax的js写法

var xmlHttp;

window.onload = function() {
	// 监听用户名失去焦点事件
	var usernameEle = document.getElementById("username");
	usernameEle.onblur = function() {
		if (usernameEle.value.length == 0) {
			document.getElementById("usernameTip").innerHTML = "亲,你的用户名不能为空!";
			return;
		} else {
			sendXmlHttp(this.value);
		}
	}
	// 监听密码失去焦点事件
	var passwordEle = document.getElementById("password");
	passwordEle.onblur = function() {
		if (passwordEle.value.length == 0) {
			document.getElementById("passwordTip").innerHTML = "亲,你的密码不能为空!";
			return;
		} else {
			document.getElementById("passwordTip").innerHTML = "";
		}
	}
	// 监听提交按钮操作
	var submitBtn = document.getElementById("submit");
	submitBtn.onclick = function() {
		if (usernameEle.value && passwordEle.value) {
			xmlHttp = GetXmlHttpObject();
			var url = "/register";
			url = url + "?username=" + usernameEle.value + "&password="
					+ passwordEle.value;
			url = url + "&sid=" + Math.random();
			xmlHttp.onreadystatechange = function() {
				if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
					alert(xmlHttp.responseText);
				}
			};
			xmlHttp.open("post", url, true);
			xmlHttp.send(null);
		} else {
			alert("请把信息填完整");
		}
	}
}

// 发送ajac请求
function sendXmlHttp(username) {
	xmlHttp = GetXmlHttpObject();
	var url = "/register";
	url = url + "?username=" + username;
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.open("post", url, true);
	xmlHttp.send(null);
}
function stateChanged() {
	if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		document.getElementById("usernameTip").innerHTML = xmlHttp.responseText;
	}
}
// 获取ajax请求
function GetXmlHttpObject() {
	var xmlHttp = null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlHttp == null) {
		alert("您的浏览器不支持AJAX!");
		return;
	}
	return xmlHttp;
}

三、Servlet后台模拟注册功能。

@WebServlet("/register")
public class register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String[] names = { "小明", "小红" };
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=UTF-8");
		String username = req.getParameter("username");
		PrintWriter writer = resp.getWriter();
		String password = req.getParameter("password");
		for (String name : names) {
			if (name.equals(username)) {
				System.out.println(username);
				writer.print("亲,用户名已经存在!");
				return;
			}
		}

		if (StringUtil.hasLength(username) && StringUtil.hasLength(password)) {
			writer.print("注册成功");
		}

	}
}



你可能感兴趣的:(js原生ajax请求代码示例)