$.ajax与SpringMVC的那点事-传参与返回
发布时间:2020-12-16 03:32:42 所属栏目:百科 来源:网络整理
导读:$.ajax请求与SpringMVC接收 application-mvc.xml配置 bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
$.ajax请求与SpringMVC接收application-mvc.xml配置 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> <!--视图解析器配置优先级 --> <property name="order" value="1" /> </bean> 方式一:请求参数为对象,接收以对象接收$.ajax请求代码 $.ajax({ url : host + '/utilitiesCharge/queryUtilitiesList.htm',type:'POST',dataType:'json',// 返回数据格式,此配置可有可无 data: {item: typeChange,companyId: companyId,tel: mobile,typeNum: typeCode,billDate: billDate,payAmount: payAmount},success:function(data,textStatus,jqXHR){ var resp = data; // data为JSON对象 },error:function(xhr,textStatus){ console.log('错误') console.log(xhr) console.log(textStatus) } SpringMVC接收代码 @RequestMapping("/queryUtilitiesList") @ResponseBody public BaseResponse queryUtilitiesList(DLUtilitiesQueryRequest request) { logger.info("request params:" + JSONObject.toJSONString(request)); } 其中,data为对象, data: {item: typeChange,payAmount: payAmount} 则SpringMVC,可直接用对象接收 DLUtilitiesQueryRequest request 方式二:请求以JSON字符串,接收讲JSON字符串转换为对象再接收$.ajax请求代码 $.ajax({ url : host + '/utilitiesCharge/queryUtilitiesList.htm',// 返回数据格式,此配置可有可无 contentType:'application/json',// 声明请求参数格式为JSON data: JSON.stringify({item: typeChange,payAmount: payAmount}),//JSON字符串 success:function(data,jqXHR){ 差异部分: contentType:'application/json',// 声明请求参数格式为JSON data: JSON.stringify({item: typeChange,//JSON字符串 SpringMVC接收代码 @RequestMapping("/queryUtilitiesList") @ResponseBody public BaseResponse queryUtilitiesList(@RequestBody DLUtilitiesQueryRequest request) { logger.info("request params:" + JSONObject.toJSONString(request)); } 差异部分: @RequestBody DLUtilitiesQueryRequest request SpringMVC返回与$.ajax接收各项代码参考上面
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |