一个验证邮箱是否已经存在的ajax
var email = document.getElementById("email"); // 获取email 文本框
var email_span = document.getElementById("email.span");
// 验证邮箱
email.onblur = function () { // 失去焦点时
// 1. 创建XMLHttpRequest对象
var xhr = null;
var emailValue = email.value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // 兼容IE6
}
// 2.准备发送
xhr.open("post","./server/checkemail.php",true); // true异步
// 2.get方法:xhr.open("get","./server/checkemail.php?email=" + emailValue , true)
// 3.发送
var param = "email=" + emailValue;
// 设置请求头(post方法才需要设置请求头)
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(param);
// 3.get方法:xhr.send(null)
// 4.设置回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 读取状态为4才执行
if (xhr.status == 200) { // 浏览器返回200才执行
var result = xhr.responseText; // 获取php页面返回值
var email_span = document.getElementById("email_span");
if (result == 0) {
email_span.innerText = "邮箱可以使用";
} else {
email_span.innerText = "邮箱不可以使用";
}
}
}
}
}