1 ajax 是什么匈勋?
ajax是一種技術方案,但并不是一種新技術膳叨。它依賴的是現(xiàn)有的CSS/HTML/Javascript洽洁,而其中最核心的依賴是瀏覽器提供的XMLHttpRequest對象,是這個對象使得瀏覽器可以發(fā)出HTTP請求與接收HTTP響應.
1.1 ajax有什么作用
我們使用XMLHttpRequest對象來發(fā)送一個Ajax請求菲嘴。來實現(xiàn)在頁面不刷新的情況下和服務端進行數(shù)據(jù)交互饿自,能夠快速,增量更新用戶界面龄坪,而無需重新加載整個瀏覽器頁面昭雌;即異步更新;這使得應用程序更快健田,更響應用戶操作烛卧。
范例:
使用GET方法;
var xhr = new XMLHttpRequest();
xhr.open('GET','/hello.json');
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if((xhr.status>=200 &&xhr.status <300)|| xhr.status ==304){
console.log(xhr.responseText);
console.log("aa");
}else{
alert("服務器異常")
console.log("bb");
}
}
}
xhr.send();
1.png
使用POST方法:
var xhr = new XMLHttpRequest();
xhr.timeou=5000;
xhr.onload = function(){
if((xhr.status>=200 &&xhr.status <300)|| xhr.status ==304){
console.log(xhr.responseText);
console.log("aa");
}else{
alert("服務器異常")
console.log("bb");
}
};
xhr.open('POST','/server',true)
xhr.send('username=xiaolhui')
2 封裝一個 ajax 函數(shù)
function ajax(opts){
var url= opts.url;
var type= opts.type || 'GET';
var dataType = opts.dataType || 'json';
var data = opts.data;
var dataStr= [];
for(var key in data){
dataStr.push(key +'='+data[key])
}
dataStr=dataStr.join('&');
var xhr=new XMLHttpRequest();
xhr.open(type,url,true);
xhr.onload=function(){
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
if(dataType==='json'){
console.log(JSON.parse(xhr.responseText))
}else{
console.log(xhr.responseText)
}
}else{
alert("服務器異常")
}
};
if(type==='GET'){
url+='?'+dataStr;
}
if(type==='POST'){
xhr.send(dataStr);
}else{
xhr.send();
}
}
ajax({
url:'/hello.json',
data:{
city:'杭州'
}
})
2.png