staffManage.js
实例化Ajax可分为五点,比较好记:
1、new一个XMLHttpRequest实例
注意兼容低版本的IE浏览器
var xhr;
if (window.XMLHttpRequest) {
xhr= new XMLHttpRequest();
} else {
xhr= new ActiveXObject(‘Microsoft.XMLHTTP');
}
2、open(method,url,asyn)
XMLHttpRequest对象的open()方法有3个参数,第一个参数指定是GET还是POST,第二个参数指定URL地址,第三个参数指定是否使用异步,默认是true,所以不用写。
3*若是post请求还要加上请求头 setRequestHeader(”Content-Type”,”application/x-www-form-urlencoded”)
4、send
调用send()方法才真正发送请求。GET请求不需要参数,POST请求需要把body部分以字符串或者FormData对象传进去。
5、onReadyStateChange
6、responseText
// 查询员工方法
var oKeyword=document.getElementById('keyword'), //员工编号
oSearchBtn=document.getElementById('search'), //查询按钮
oSearchRes=document.getElementById('searchResult'); //反馈结果显示
// 查询员工按钮点击事件
oSearchBtn.onclick=function(){
searchStaff();
}
// 创建查询员工方法
function searchStaff(){
//var xhr=new XMLHttpRequest();
//标准写法和IE写法混在一起,可以兼容低版本的IE浏览器
var xhr;
if (window.XMLHttpRequest) {
xhr= new XMLHttpRequest();
} else {
xhr= new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('GET','serverjson.php?number='+oKeyword.value);
xhr.send();
//当创建了XMLHttpRequest对象后,要先设置onreadystatechange的回调函数。在回调函数中,通常我们只需通过readyState === 4判断请求是否完成,如果已完成,再根据status === 200判断是否是一个成功的响应。
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status=200){
var data=JSON.parse(xhr.responseText); //json解析方法JSON.parse 或者 eval('('+xhr.responseText+')')
oSearchRes.innerHTML=data.msg;
}
}
}
}
// 增加员工
var oAddnumber=document.getElementById('add-number'), //员工编号
oAddname=document.getElementById('add-name'), //员工姓名
oAddsex=document.getElementById('add-sex'), //员工性别
oAddjob=document.getElementById('add-job'), //员工职位
oAddSearch=document.getElementById('add-search'), //增加员工按钮
oAddResult=document.getElementById('add-resultshow'); //反馈结果显示
// 增加员工按钮点击事件
oAddSearch.onclick=function(){
createStaff();
}
// 创建增加员工方法
function createStaff(){
var xhr;
if(xhr.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('POST','serverjson.php');
//这里注意key=value的等于号两边不要出现空格,会出现错误
var data='name='+oAddname.value
+'&number='+oAddnumber.value
+'&sex='+oAddsex.value
+'&job='+oAddjob.value;
//在open和send之间设置Content-Type
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(data);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status=200){
var data=JSON.parse(xhr.responseText);
if(data.success){
oAddResult.innerHTML=data.msg;
}else{
oAddResult.innerHTML='出现错误:'+data.msg;
}
}else{
alert('发生错误!'+xhr.status)
}
}
}
}









