关于ajax发送请求和后台服务器接收的数据类型

  • Post author:
  • Post category:其他


<td nowrap><a style="color='blue'" onMouseOver="style:this.style.cursor='hand';this.style.color='green';this.style.textDecorationUnderline=true"
    	onmouseout = "this.style.textDecorationUnderline = false;this.style.color='blue'"
    	onclick="MM_openBrWindow1('
http://10.2.10.13:8096/trace/tuwen/getPreviewUrlByCode/<%=rs1.getString("sseab").trim()%>
;','<%=rs1.getString("sseab").trim()%>')"><%=rs1.getString("sseab").trim()%>    <%=currdate%></a></td>


function MM_openBrWindow1(theURL,winName,features) { 
	 //v2.0
	
	 var hh = "56800010656512";
	 $.ajax({
	        url: '
http://10.2.10.13:8096/trace/tuwen/getPreviewUrlByCode/56800010656512
',
	        headers: {
	             'Username': "20218888",
	             'Password': "GREE@321"
	         },
	         type: 'get',
	         dataType: 'JSON',
	         contentType: 'application/json;charset=UTF-8',
	         success : function(data) {
	        	
	            if (data.code=="200") {
	            	 
	            if (data.data.number!=null){
	            	 window.open(data.data.url);
	            }
	           	 console.log("=data======="+data.data.url);
	           	console.log("=data.data.number======="+data.data.number);
	          
	            } else {
	                 alert(data.message);
	             }
	         },
	         error : function(data) {
	             console.log(data);
	         }
	        
	  });
	  
	}

关于ajax发送请求和后台服务器接收的数据类型



1.ajax发送请求到后台

前端发送ajax的请求的参数有几种方式:

1.get

在url路径上面拼接参数

2.post

把参数放到data:

2.1如果是多个参数的话就封装成对象

2.2如果是

//这个是对应着下面后台的接收
$.ajax({

    url: "
http://172.16.19.80:3002/ttdsct399/getUrlToJson"
;,
    type: 'POST',
    //Access-Control-Allow-Origin: *,
    //Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept;
    async: false,
    /* xhrFields:{
    	'Access-Control-Allow-Origin': '*'
	 }, */
    dataType : 'json',
    contentType: "application/json;charset=UTF-8",
    //JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
    data : JSON.stringify(jsonData),
    success : function(datas) {
    	
    console.log("200");
    console.log("datas===="+datas);
    // var jsonobj=eval(s);
    var resultNewJsonData=$.parseJSON(datas);
    var result501Data=[];
    var result500Data=[];
    var result200Data=[];
    var result200DataShowUser=[];
  
  //解析返回的json, 并且重新封装新的json 
   console.log("datas:"+resultNewJsonData);
   console.log("datas=:"+JSON.stringify(datas));
    for(var i=0;i<datas.length;i++){
	    if(datas[i].status=="200"){
			 console.log("200进来了");
			 result200Data.push({
		         "slcp":"400",
		         "ortp":"1",
		         "koor":"3",
		        /*  "oset":"0",
		         "shpm":" ", */
				 "slso" : datas[i].orno,
				 /* "pono" : datas[i].orrows[0][0],
				 "sqnb" : datas[i].orrows[0][1], */
				 "flag":"1"
				 //"cndt":currentDateStr
			 });
			 result200DataShowUser.push({
			    "订单" : datas[i].orno,
				/* "行号" : datas[i].orrows[0][0],
				"序号" : datas[i].orrows[0][1] */
			 });
		}else if(datas[i].status=="501"){
			alert("=======");
		    console.log("501进来了");
		    result501Data.push({
				"订单" : datas[i].orno,
				/* "行号" : datas[i].orrows[0],
				"序号" : datas[i].orrows[1] */
		    });
		}else if(datas[i].status=="500"){ 
		    alert("======"+datas[i].status);
		    console.log("500进来了");
		    alert("请检查Baan服务器");
		    result500Data.push({
			"原因:" : datas[i].message
			
	    });
	}
	    
    }
    console.log("200="+JSON.stringify(result200Data));
    console.log("20="+JSON.stringify(result200DataShowUser));
    console.log("501="+JSON.stringify(result501Data));
    console.log("500="+JSON.stringify(result500Data));
    updateFlag(result200Data,result501Data,result200DataShowUser,result500Data);
},
error : function(datas){
	console.log("datas======:"+JSON.stringify(datas));
	alert(datas.status);
}
});

标准一点的ajax

$.ajax({
       url: apiUrl + '/ttdsct437/deleteCustomizedApprovalRecord?bhnos='+chk_value,
       headers: {
           'x-authorization': "e5df21d27f0b407d87a13788e7e673d9"
       },
       type: 'GET',
       dataType: 'JSON',
       contentType: 'application/json;charset=UTF-8',
       success : function(data) {
           if (data.status=="200") {
              alert("删除成功!");
              location.reload();
           } else {
               alert(data.message);
           }
       },
       error : function(data) {
           console.log(data);
       }
   });

参数版ajax:

function doSave(id, bhno, qssj, oldyc) {
   var whry = "<%=user %>";
   //td的兄弟节点
   var a = $("input[type='button'][id='"+id+"']").parent().siblings();
   var ycqk = a[14].children[0].value;
   if(ycqk.trim() == oldyc) {
      alert("修改前后的值没变,请重新选择!")
   } else {
      //alert(ycqk+";"+bhno+";"+qssj);
      var params = {
          'rowsid': id,
          'bhno': bhno,
          'qssj': qssj,
          'ycqk': ycqk,
          'whry': whry,
      };
      $.ajax({
          url: apiUrl + '/ttdsct437/updateCustomizedApprovalRecord',
          headers: {
               'x-authorization': "e5df21d27f0b407d87a13788e7e673d9"
           },
           type: 'POST',
           dataType: 'JSON',
           contentType: 'application/json;charset=UTF-8',
           data : JSON.stringify(params),
           success : function(data) {
              if (data.status=="200") {
                 alert("修改成功!");
                 doCancel();
              } else {
                   alert(data.message);
               }
           },
           error : function(data) {
               console.log(data);
           }
       });
   }
}

另一种发送请求方式:

//批量导出
function doExcel() {
   var qssjl = $("#qssjl").val();
   var qssjr = $("#qssjr").val();
   if(qssjl == "" || qssjr == ""){
      alert("签审时间不能为空!!!");
   }
   if(qssjl != "" && qssjr != ""){
       var params = {
          'qssjl': qssjl,
          'qssjr': qssjr,
       };
       var excelUrl = apiUrl + '/ttdsct437/exportCustomizedApprovalRecord';
       var xhr = new XMLHttpRequest();
       xhr.open('post', excelUrl, true);
       xhr.setRequestHeader('x-authorization','e5df21d27f0b407d87a13788e7e673d9');
       xhr.setRequestHeader('Content-Type', 'application/json');
       xhr.send(JSON.stringify(params));
       xhr.responseType = 'blob';
       xhr.onload = function(){
          if(this.status === 200){
             var blob = this.response;
              var reader = new FileReader();
              reader.readAsDataURL(blob);
              reader.onload = function(e){
                 var a = document.createElement('a');
                  a.download = '客户化签审记录.xls';
                  a.href = e.target.result;
                  $('body').append(a);
                  a.click();
                  $(a).remove();
              };
              alert("导出成功!")
          } else {
             alert('导出失败,请稍后重试!');
          }
       };
   }
}

ajax里面或者function里面嵌套html,然后全选

function doFind(){
   $.ajax({
       url: apiUrl + '/ttdsct437/getCustomizedApprovalRecord?pageNum='+pageNum+'&pageSize='+pageSize,
       headers: {
            'x-authorization': "e5df21d27f0b407d87a13788e7e673d9"
        },
        type: 'GET',
        dataType: 'JSON',
        contentType: 'application/json;charset=UTF-8',
        success : function(data) {
           if (data.status=="200") {
              list = data.data;
              var listHtml = '<tr>'
                         +'<th><input type="checkbox" name="" id="check_all" οnclick="selectAll()">删除</th>'
                         +'<th>类型</th>'
                         +'<th>编号</th>'
                         +'<th>签审对象名称</th>'
                         +'<th>活动名称</th>'
                         +'<th>角色</th>'
                         +'<th>路由</th>'
                         +'<th>签审意见</th>'
                         +'<th>签审时间</th>'
                         +'<th>编制人员</th>'
                         +'<th>编制用户邮箱</th>'
                         +'<th>编制部门</th>'
                         +'<th>审核人员</th>'
                         +'<th>版本</th>'
                         +'<th>异常问题</th>'
                         +'<th style="color: red;">修改异常信息</th>'
                         +'<th>维护日期</th>'
                         +'<th>维护人员</th>'
                         +'</tr>';
                         for (var i = 0; i < list.length; i++) {
                 var obj = list[i].bhno+";"+list[i].qssj;
                 listHtml += '<tr><td><input type="checkbox" name="ids" class="check_item" value="'+list[i].bhno+";"+list[i].qssj+'"/></td>'
                          //+ '<a href="#" οnclick="doModify(\''+obj+'\')">修改</a> <a href="#" οnclick="doCancel()">取消</a></td>';
                          //+ '<a href="#" οnclick="doModify(\''+obj+'\')">修改</a></td>';
                 listHtml += '<td>'+list[i].leix+'</td>';
                 listHtml += '<td>'+list[i].bhno+'</td>';
                 listHtml += '<td>'+list[i].qsdx+'</td>';
                 listHtml += '<td>'+list[i].hdmc+'</td>';
                 listHtml += '<td>'+list[i].jues+'</td>';
                 listHtml += '<td>'+list[i].luyo+'</td>';
                 listHtml += '<td>'+list[i].qsyj+'</td>';
                 listHtml += '<td>'+list[i].qssj+'</td>';
                 listHtml += '<td>'+list[i].bzry+'</td>';
                 listHtml += '<td>'+list[i].bzyh+'</td>';
                 listHtml += '<td>'+list[i].bzbm+'</td>';
                 listHtml += '<td>'+list[i].shry+'</td>';
                 listHtml += '<td>'+list[i].banb+'</td>';
                 //listHtml += '<td οndblclick="show(this)">'+list[i].ycms+'</td>';
                 listHtml += '<td>异常'+list[i].ycwt+":"+list[i].ycms+'</td>';
                 listHtml += '<td><input id="'+list[i].rowsid+'" type="button" value="修改" οnclick="doModify(this.id, \''+list[i].bhno+'\', \''+list[i].qssj+'\')"></td>';
                 listHtml += '<td>'+list[i].whrq+'</td>';
                 listHtml += '<td>'+list[i].whry+'</td>';
                 listHtml += '</tr>';
              }
              if (list.length > 0) {
                 pageSum = Math.ceil(list[0].dataSum / pageSize);//总页数 
                 $("#dataSum").val(list[0].dataSum);
                 $("#pageNum").val(pageNum);
                 $("#pageSum").val(pageSum);
              } else {
                 $("#dataSum").val(0);
                 $("#pageNum").val(0);
                 $("#pageSum").val(0);
              }
              $('#tableList').html(listHtml);
           } else {
                alert(data.message);
            }
        },
        error : function(data) {
            console.log(data);
        }
    });
}



//js实现全选/全不选
function selectAll() {
	var inputNodes = document.getElementsByClassName("check_item");
	var stateNode = document.getElementById("check_all");

	for (var i = 0; i < inputNodes.length; i++) {
		inputNodes[i].checked = stateNode.checked;
	}
}

//单个单选框绑定点击事件
$(document).on("click",".check_item",function(){
    var flag=$(".check_item:checked").length==$(".check_item").length;
	$("#check_all").prop("checked",flag);
});


2.后台接收数据


先写一个接口,在写接口的实现类。



2.1接口
@RequestMapping("/ttdsct399")
@FeignClient("baanservicestandard197")
@CrossOrigin("*")
public interface Ttdsct399Api extends IErpCurdApi<Ttdsct399> {
    //从前端传过来是一个json字符串,但是我们在后端接收是才用lits转换成一个对象
    @PostMapping("/getUrlToJson")
    String getUrlToJson(List<String> list);

}

2.2接口实现类

@Api(tags = {"Ttdsct399表CRUD接口"},description="开票订单号确认中间表(耿艳辉)增删改查接口<b>,主键:slcp(来源后勤公司),ortp(订单类型),koor(订单种类),slso(销售订单/仓单)</b>")
@RestController
public class Ttdsct399ApiImpl extends ErpCrudApiImpl<Ttdsct399ServiceImpl, Ttdsct399> implements Ttdsct399Api {

    @Override
    @ApiOperation("天猫开票")
    public String getUrlToJson(@RequestBody List<String> list) {
        System.out.println("============"+list);
     
       
        
     //  JSON.parseObject,是将Json字符串转化为相应的对象;JSON.toJSONString则是将对象转化为Json字符串。
      //方法封装
        String resl = HttpClientUtil.doPostJson("发送的url", JSON.toJSONString(list));
       
           return resl;
    }


}

在编写一个类HttpClientUtil。在类中编写doPostJson方法

public static String doPostJson(String url, String json) {
   // 创建Httpclient对象
   CloseableHttpClient httpClient = HttpClients.createDefault();
   CloseableHttpResponse response = null;
   String resultString = "";
   try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPost.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPost);
      根据字符集重新编码成正确的,转换为统一的utf-8
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      try {
         response.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   return resultString;
}

除了用CloseableHttpClient,还可以用OkHttpClient。

/* String url = "
http://10.3.0.104:35000/SLSOrder_Conf_state"
;;
 OkHttpClient okHttpClient = new OkHttpClient();
 final Request request = new Request.Builder()
         .url(url)
         .get()//默认就是GET请求,可以不写
         .build();
 Call call = okHttpClient.newCall(request);
 call.enqueue(new Callback() {
     @Override
     public void onFailure(Call call, IOException e) {

         System.out.println("onResponse================");

     }

     @Override
     public void onResponse(Call call, Response response) throws IOException {
         System.out.println("onResponse"+ response.body().string());
     }




 });*/

例子:

@SuppressWarnings("unchecked")
	public static Map<String, List<OrnoSelectItemInfoDTO>> getPdnoSelectItem(List<String> resultMitm){
		HttpClient client = new HttpClient();		
		PostMethod postMethod = null;
		Map<String, List<OrnoSelectItemInfoDTO>> map2 = new HashMap<>();
		String apiResult = "";
		String result1 = "";
		String url = "";
		try{
			System.out.println("=====resultMitm====="+resultMitm);
			String jsonString2= JSON.toJSONString(resultMitm);
			System.out.println("=====jsonString2====="+jsonString2);
			RequestEntity entity = new StringRequestEntity(jsonString2,"application/json","UTF-8");	
			url = "
http://localhost:3002/PackageInfoMitmApi/gettuwenbytuhao"
;;
			//url = "
http://baanapp.gree.com/BAANSERVICESTANDARD197/PackageInfoMitmApi/gettuwenbytuhao"
;;
			postMethod = new PostMethod(url);
			postMethod.setRequestHeader("x-authorization","e5df21d27f0b407d87a13788e7e673d9");
			postMethod.setRequestHeader("Content-Type","application/json");					
			postMethod.setRequestEntity(entity);
			client.executeMethod(postMethod);
			if(postMethod.getStatusCode()==HttpStatus.SC_OK){
			//响应成功
				apiResult = postMethod.getResponseBodyAsString();//调用返回结果				
				JSONObject json = JSONObject.parseObject(apiResult);				
				List<OrnoSelectItemInfoDTO> result = new ArrayList<>();				
				for (Entry<String, Object> entryMitm : json.entrySet()) {				
					JSONArray jsonArray = JSONArray.parseArray(entryMitm.getValue().toString());
					String object_str = JSON.toJSON(entryMitm.getValue()).toString();//2020 10/28
					List<OrnoSelectItemInfoDTO> list= JSON.parseArray(object_str, OrnoSelectItemInfoDTO.class);				
					result = jsonArray.toJavaList(OrnoSelectItemInfoDTO.class);
					List<OrnoSelectItemInfoDTO> ornoSelectItemInfoDTOList = new ArrayList<>();
					 for (OrnoSelectItemInfoDTO rDto : result) {
						 OrnoSelectItemInfoDTO ornoSelectItemInfoDTO = new OrnoSelectItemInfoDTO();
						 ornoSelectItemInfoDTO.setCwoc(rDto.getCwoc());
						 ornoSelectItemInfoDTO.setDsca(rDto.getDsca());
						 ornoSelectItemInfoDTO.setHebin(rDto.getHebin());
						 ornoSelectItemInfoDTO.setHeshul(rDto.getHeshul());
						 ornoSelectItemInfoDTO.setItem(rDto.getItem());
						 ornoSelectItemInfoDTO.setLyno(rDto.getLyno());
						 ornoSelectItemInfoDTO.setMitm(rDto.getMitm());
						 ornoSelectItemInfoDTO.setPrdt(rDto.getPrdt());
						 ornoSelectItemInfoDTO.setScpc(rDto.getScpc());
						 ornoSelectItemInfoDTO.setQrdr(rDto.getQrdr());
						 ornoSelectItemInfoDTO.setXuno(rDto.getXuno());
						 ornoSelectItemInfoDTO.setTimeString(rDto.getTimeString());
						 ornoSelectItemInfoDTOList.add(ornoSelectItemInfoDTO);
//						 System.out.println("=====ornoSelectItemInfoDTOList====="+ornoSelectItemInfoDTOList);
					 }					
					map2.put(entryMitm.getKey(), ornoSelectItemInfoDTOList);
				}
				//System.out.println("=====map2====="+map2);
			}else{
				System.out.println("接口请求失败");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return map2;
	}



版权声明:本文为weixin_44227650原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。