一、JQuery 发送 Ajax 请求

■ 对于 get 和 post 请求,jQuery 内部封装了 Ajax 请求的 4 个步骤和数据格式的设置

■ 对于 Ajax 通用请求,jQuery 内部封装了 Ajax 请求的 4 个步骤和数据格式设置、超时设置、请求失败设置

(1)jquery-server 的 get 请求:

  • 客户端 html 处理:

        $('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');});
    Plain text
  • 服务端 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));});
    Plain text

(2)jquery-server 的 post 请求:

  • 客户端 html 处理:

        $('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');});
    Plain text
  • 服务端 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));});
    Plain text

(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(' 请求出错 ');}});});
    Plain text
  • 服务端 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)});
    Plain text

学习 AJAX 必知必会(4)~JQuery 发送 Ajax 请求的