微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

$.ajax与SpringMVC的那点事-传参与返回

$.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接收

各项代码参考上面

  1. 如果返回的是一个网页内容,则@ResponseBody不用声明,返回字符串(即页面地址如:return "/web/xxx")
  2. 如果返回的是一个JSON,则要声明@ResponseBody:
  • 如果返回的是一个JSON字符串,则ajax的success中的data参数为字符串,
  • 如果返回的是JSON对象,则data为对象。
  • 由于有@RresponseBody标示,SpringMVC会将头信息中的Content-Type:application/x-www-form-urlencoded(认值)改为application/json;,即返回为JSON格式,所以ajax的dataType:"json"可有可无。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐