学习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请求:

  • 客户端html处理:

        //$.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');
        });
    
  • 服务端jquery-server请求的处理:

    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请求:

  • 客户端html处理:

      $('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请求的处理:

    //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请求:

  • 客户端html处理:
 <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>
  • 服务端jquery-server请求的处理:
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对象)

  • 客户端html处理:

    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));
    });
    

posted @ 2022-01-22 11:45  一乐乐  阅读(203)  评论(0编辑  收藏  举报