ajax = Asychronous JavaScript And XML (局部)异步的形式操作 xml,现在处理的数据格式都是json了
A. AJAX 步骤
1.浏览器
2.ajax对象
3.ajax.open(method, url, true);
4.ajax.send();
5.onreadystatechange 0 1 2 3 4
6.status == 200 403 503
创建对象
var xhr;
if(window.XMLHttpREquest){
xhr = new XMLHttpRequest();
}else{
//IE6、IE5
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
发送请求
xhr.open(method, url, async);
xhr.send();
------------------------------------------------
method:'GET' 和 'POST';
url: 文档在服务器的地址
async:true(异步),false(同步)
1.) GET
xhr.open('GET','getList.php',true);
xhr.send();
避免数据缓存,给url添加唯一的标识。
xhr.open('GET', 'getList.php?id='+Math.randow(), true)
xhr.send();
请求时,发送信息
xhr.open('GET', 'getList.php?name=kiwi&age=27', true)
xhr.send();
2.) POST
xhr.open('POST', 'post.php', true);
xhr.send();
post类似表单信息时,需要向请求添加HTTP头
xhr.open('POST', 'post.php', true);
xhr.setRequestHeader('Content-type', 'application/x--www-form-urlencoded');
//setRequestHeader(头名称, 头值)
xhr.send('user=kiwi&age=27');
响应
responseText: 获取字符串形式的响应数据;
responseXML: 获得 XML 形式的响应数据;
onreadystatechange:readystate 状态改变的事件触发器
readystate
0-->未初始化,未调用send()方法;
1-->未读取,已调用send(),正在发送请求
2-->已读取,send()方法执行完成,接受到全部响应内容
3-->交互中,正在解析响应内容
4-->完成,响应内容解析完成
服务器返回的状态码status
404 = 文本未找到
200 = 成功
500 = 服务器内部错误
304 = 资源未被修改
...
B. 封装 AJAX 兼容性函数
function ajaxFunc(method, url, data, callback, flag){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
if(method == 'GET'){
xhr.open(method, url + '?' + data, flag);
xhr.send();
}else if(method == 'POST'){
xhr.open(method, url, flag);
xhr.setRequestHeader('Content-type', 'application/x--www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
//console.log(typeof xhr.responseText)-->sting
callback(xhr.responseText)
}
}
}
使用例子
<form>
<input type="text" name="name" id="name">
<input type="text" name="age" id="age">
<input type="submit" value="提交" id="sub">
</form>
<button id="btn">获取</button>
<ul id="ul"></ul>
callback
function showList(data){
var value = JSON.parse(data);
var str = '';
value.forEach(function(ele, index){
console.log(ele,index)
str += '<li>'+ele.title + '--' + ele.data +'</li>';
})
ul.innerHTML = str;
}
function showPerson(data){
console.log(data);
alert(data);
}
调用
btn.onclick = function(){
//ajaxFunc(method, url, data, callback, flag)
ajaxFunc('GET','./getList.php','', showList,true);
}
sub.onclick = function(e){
e.preventDefault();
var data = 'name=' + name.value +'&age=' + age.value;
//ajaxFunc(method, url, data, callback, flag)
ajaxFunc('POST', './post.php', data, showPerson, true)
}
补充状态码
200 服务器响应正常
304 该资源在上次请求之后没有任何修改(这通常用于浏览器的缓存机制,使用 GET 请求时尤其需要注意)
400 无法找到请求的资源
401 访问资源的权限不够
403 没有权限访问资源
404 需要访问的资源不存在
405 需要访问的资源被禁止
407 访问的资源需要代理身份验证
414 请求的 URL 太长
500 服务器内部错误