Ajax

1 ajax 是什么?

ajax是一種技術(shù)方案,但并不是一種新技術(shù)。它依賴的是現(xiàn)有的CSS/HTML/Javascript,而其中最核心的依賴是瀏覽器提供的XMLHttpRequest對象,是這個對象使得瀏覽器可以發(fā)出HTTP請求與接收HTTP響應(yīng).

1.1 ajax有什么作用

我們使用XMLHttpRequest對象來發(fā)送一個Ajax請求。來實(shí)現(xiàn)在頁面不刷新的情況下和服務(wù)端進(jìn)行數(shù)據(jù)交互,能夠快速,增量更新用戶界面,而無需重新加載整個瀏覽器頁面;即異步更新;這使得應(yīng)用程序更快,更響應(yīng)用戶操作。

范例:

使用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("服務(wù)器異常")
                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("服務(wù)器異常")
                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("服務(wù)器異常")
            }
        };
        if(type==='GET'){
            url+='?'+dataStr;
        }
        if(type==='POST'){
            xhr.send(dataStr);
        }else{
            xhr.send();
        }
    }
    ajax({
        url:'/hello.json',
        data:{
            city:'杭州'
        }
    })
2.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容