天天看點

學習AJAX必知必會(4)~JQuery發送Ajax請求、ajax使用fetch函數(傳回值是Promise對象)

作者:一樂樂

歡迎大家來一樂樂的部落格園

一、JQuery發送Ajax請求

■ 對于get和post請求,jQuery内部封裝了Ajax請求的4個步驟和資料格式的設定

■ 對于Ajax通用請求,jQuery内部封裝了Ajax請求的4個步驟和資料格式設定、逾時設定、請求失敗設定

(1)jquery-server的get請求:

  • 用戶端html處理:
    //$.get(url, [data], [callback], [type])
    
        $('button').eq(0).click(function () {
           //$get方法的回調參數接收一個data作為參數---是服務端響應回來的資料(響應體),然後設定響應的資料格式為json
           $.get('http://127.0.0.1:8000/jquery-server', {a:1, b:2}, function (data) {
               console.log(data);
           }, 'json');
        });
               
  • 服務端jquery-server請求的處理:
    app.get('/jquery-server', (request, response) => {
        //設定響應頭(允許跨域)
        response.setHeader('Access-Control-Allow-Origin', '*');
        //響應回去一個json對象
        const data = {
            name: '小黑',
            age: 18,
            sex: '男'
        };
        //設定響應體
        response.send(JSON.stringify(data));
    });
               

(2)jquery-server的post請求:

  • //$.post(url, [data], [callback], [type])
    
        $('button').eq(1).click(function () {
            //$get方法的回調參數接收一個data作為參數---是服務端響應回來的資料(響應體),然後設定響應的資料格式為json
            $.post('http://127.0.0.1:8000/jquery-server', {a:1, b:2}, function (data) {
                console.log(data);
            }, 'json');
        });
               
  • app.post('/jquery-server', (request, response) => {
        //設定響應頭(允許跨域)
        response.setHeader('Access-Control-Allow-Origin', '*');
        //響應回去一個json對象
        const data = {
            name: '小白',
            age: 18,
            sex: '男'
        };
        //設定響應體
        response.send(JSON.stringify(data));
    });
               

✿(3)jquery-server的通用ajax請求:

  • $('button').eq(2).click(function () {
         $.ajax({
             url: 'http://127.0.0.1:8000/jquery-server/delay',//請求路徑
             data: {a:1,b:2,c:3},//請求參數(請求體)
             type:'get',//請求方式
             headers:{'Content-Type': 'application/x-www-form-urlencoded'},//請求頭
             dataType: 'json',//請求的資料格式
             timeout:4000,//逾時設定
             success: function (data) {//請求成功的回調
                 console.log(data);
             },
             error: function () {//請求失敗的回調
                 console.log('請求出錯');
             }
         });
      });
               
  • //jquery-server請求逾時處理
    app.get('/jquery-server/delay', (request, response) => {
        //設定響應頭(允許跨域)
        response.setHeader('Access-Control-Allow-Origin', '*');
        //響應回去一個json對象
        const data = {
            name: '小遲',
            age: 18,
            sex: '男'
        };
        //設定響應體
        setTimeout(() => {
            response.send(JSON.stringify(data));
        }, 3000)
    });
               

(4) jQuery 發送jsonp請求:

<button>點選發送 jsonp 請求</button>
 <div id="result"></div>

 <script>
    $('button').eq(0).click(function(){
	 // jquery封裝的ajax的jsonp請求需要有一個callback參數
        $.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function(data){
            $('#result').html(`
                名稱: ${data.name}<br>
                 校區: ${data.city}
             `);
        });
     });
 </script>
           
app.all('/jquery-jsonp-server',(request, response) => {
    // response.send('console.log("hello jsonp")');
    const data = {
        name:'小明',
        city: ['北京','上海','深圳']
    };
    //将資料轉化為字元串
    let str = JSON.stringify(data);
    //接收 callback 參數
    let cb = request.query.callback;

    //傳回結果
    response.end(`${cb}(${str})`);
});
           

二、ajax使用fetch函數(類似axios,傳回值是Promise對象)

  • btn2.onclick = function () {
            fetch('http://127.0.0.1:8000/fetch-server?a=1&b=2',{
                method: 'post',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                //請求體body(資料格式可以是字元串,也可以是json對象)
                // body: 'name=小明&age=16&sex=男'
                body: {
                    name: '小明',
                    age: 16,
                    sex: '男'
                }
            }).then(response => {
                //若響應回來的資料格式是字元串,響應回來的資料,需要通過text方法轉化一下,json格式的話,則需要通過json方法轉化一下
                return response.text();
                // return response.json();
            }).then(response => {
                console.log(response);
            })
        }
               
  • 服務端fetch函數的請求處理:
    app.post('/fetch-server', (request, response) => {
        //設定響應頭(允許跨域)
        response.setHeader('Access-Control-Allow-Origin', '*');
        //響應回去一個字元串對象
        const data = '小白白';
        response.send(data);
        //響應回去一個json對象
        // const data = {
        //     name: '小白',
        //     sex: '男'
        // };
        // response.send(JSON.stringify(data));
    });
               

● 文章來源于:一樂樂的部落格園

● 轉載請注明出處