Ajax请求的常用方式记录(作为常用copy模板)

一、Get 请求的模板(不带参数,普通请求,接收返回JSON格式的反馈数据)

 1   $.ajax({
 2     type: 'GET',
 3     url: ipprefix + '/GetAllTestTasksStatusData',
 4     dataType: 'json', //期望的后端返回数据格式
 5     async: false,
 6     success: function (res) {
 7       result = res;
 8     },
 9     error: function (xhr, status, error) {
10       console.error('Request failed:', status, error);
11     }
12   });

 

二、Get 请求的模板(带请求参数,接收返回JSON格式的反馈数据)

 1 var result = null;
 2 $.ajax({
 3   type: 'GET',
 4   url: ipprefix + '/GetAllDataIndicators',
 5   data: {
 6     taskType: 1  // 这里添加你的请求参数
 7   },
 8   dataType: 'json', // 期望的后端返回数据格式
 9   async: false,
10   success: function (res) {
11     result = res;
12   },
13   error: function (xhr, status, error) {
14     console.error('Request failed:', status, error);
15   }
16 });

 

三、GET请求模板(表单提交,请求参数格式:x-www-form-urlencoded,设置接收反馈的数据格式为二进制blob,再转换为图片)

 1  // 发起AJAX请求获取图片
 2     $.ajax({
 3       type: 'GET',
 4       url: ipprefix_img + '/testUnmannedSystem/image/download',
 5       data: {
 6         path: result.data.usimage  // 这是x-www-form-urlencoded格式的参数
 7       },
 8       contentType: 'application/x-www-form-urlencoded', // 设置正确的contentType
 9       xhrFields: {
10         responseType: 'blob' // 重要!告诉jQuery我们要接收二进制数据
11       },
12       success: function (response) {
13         // 创建图片URL
14         const imageUrl = URL.createObjectURL(response);
15         console.log('无人系统图片处理后的地址imageUrl',imageUrl); 
16         //结果:无人系统图片处理后的地址imageUrl blob:http://172.18.54.213:2888/5eb237ec-b911-4f10-a5fe-5a4bebfc6de9
17         // 创建img元素并设置src
18         const imgElement = $('<img>', {
19           src: imageUrl,
20           alt: '无人机系统图片',
21           style: 'width:92%;height:88%; background-color: rgba(20, 255, 243, 0.53);background-size:cover;background-repeat: no-repeat;background-position:center;border:1.5px solid rgba(20, 255, 243, 1);' 
22 
23         });
24 
25         // 添加到容器中
26         $('#row_1_1').empty().append(imgElement);
27       },
28       error: function (xhr, status, error) {
29         console.error('图片加载失败:', error);
30         $('#row_1_1').html('<p>图片加载失败,请稍后再试</p>');
31       }
32     });

 

四、POST请求(JSON格式请求参数,接收的返回数据也是JSON格式)

 1   $.ajax({
 2     type: 'POST',
 3     url: ipprefix + '/GetCameraInfo',
 4     data: JSON.stringify(
 5       {
 6         "testfieldid": Number(clickedTestFieldId)
 7       }
 8     ),
 9     contentType: 'application/json',
10     async: false,
11     success: function (res) {
12       result = res;
13     },
14     error: function (xhr, status, error) {
15       console.log('Error:', error);
16     }
17   });

 

posted @ 2025-05-14 16:18  上清风  阅读(25)  评论(0)    收藏  举报