Ajax之深入瞭解

    上一節,我們說了一些Ajax的基礎知識,包括常用的get方法,現在,我們接着來講講post方法,以及利用get方法或post方法實現分頁顯示的功能。
    我們使用的是nodejs,去nodejs官網下載安裝後,在webstrom編寫代碼,將所有代碼放在public文件夾裏,然後在terminal控制檯開啓服務(npm start),之後在網頁上輸入localhost:3000/文件名.html。
    以下我們來說說get和post兩種方法的區別。詳見代碼
<script>
    //get方法
    //創建Ajax對象
    var xhr = new XMLHttpRequest();
    //創建鏈接
    xhr.open('get','/getcity?city='+city.value);
    //發送請求
    xhr.send();
    //接收返回值
    xhr.onreadystatechange = function(e){
        if(xhr.readyState == 4){//完成
            if(xhr.status == 200){//成功
                alert(xhr.response)
            }
        }
        e.preventDefault();
    };
    //get方法
    //創建Ajax對象
    var xhr = new XMLHttpRequest();
    //創建鏈接
    xhr.open('post','/postcity');
    //添加請求頭
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    //發送請求
    xhr.send('city='+city.value);
    //接收返回值
    xhr.onreadystatechange = function(e){
       if(xhr.readyState == 4 && xhr.status == 200){
           alert(xhr.response);
       }
       e.preventDefault();     
    };      
</script>

作爲前端程序員,後臺的數據我們很少涉足,但是有些接口還是需要了解一些,畢竟,前端和後臺的分解不是那麼明顯,下面我們簡單的寫兩個接口比較、瞭解一下。

//get
router.get('/getcity',function(req, res, next){
  var city = [{value:'beijing', name:'北京'},{value:'shanghai', name:'上海'}];
  res.send(city);
  res.end();
});

//post
router.post('/postcity',function(req, res, next){
  var city = req.body.city;
  console.log(city);
  res.send('您選擇的城市是'+city);
  res.end();
});

以上就是對Ajax的小小總結,接下來我們來寫一個分頁顯示的實例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        a{
            text-decoration: none;
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 1px solid #ccc;
            text-align: center;
            margin: 5px;
            color: red;
        }
        ul{
            list-style: none;
        }
    </style>
</head>
<body>
<div id="box">
</div>
</body>
<script src="../routes/data1.js"></script>
<script>

    var size = 10;
    document.body.addEventListener('click',function(e){
        var e = e || event;
        if(e.target.tagName == 'A'){

            getData(parseInt(e.target.innerText));
        }
        e.preventDefault();
    });
    getData(1);
    function getData(index){
        var xhr = new XMLHttpRequest();
        xhr.open('get','/song?index='+index+'&size='+size);
        xhr.responseType = 'json';
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                doResult(xhr.response);
            }

        };
        xhr.send();
    }
    function doResult(data){
        var json = data;
        var html = '';
        for(var i = 1; i <= json.count; i++){
            html += '<a href="javascript:;">'+ i +'</a>'
        }
        var box = document.getElementById('box');
        box.innerHTML = html;
        var ul = document.createElement('ul');
        box.appendChild(ul);
        json.data.forEach(function(item){
            var li = document.createElement('li');
            li.innerHTML = '<img src="'+ item.cimgurl +'"/>';
            ul.appendChild(li);
        })

    }
</script>
</html>

後臺接口

router.get('/song', function(req, res, next){
  var index = req.query.index;
  var size = req.query.size;
  var count = travel.length/size;
  console.log(index +''+ size);
  var dataPage = travel.slice((index -1)*size, index * size);
  res.contentType('application/json');
  res.send({allrecord:travel.length,count:count,data:dataPage,index:index});
  res.end();
});

圖片資源是一個單獨的文件夾,由於內容太多,這裏我就不再上傳,有興趣的同學可以自己試試哦

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章