百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 介绍Spring中ajax与后台传输数据的几种方式
分享文章到:

介绍Spring中ajax与后台传输数据的几种方式

发布时间:12/01 来源:未知 浏览: 关键词:

ajax栏目介绍与后台传输数据的办法

引荐(免费):ajax

比来写ajax与后台传输数据的时候碰到了一个问题,我想ajax以json的方式把数据传输个后台,后台用map的情势接收,然后也以map的情势传回数据。可是不断碰到前台报(*)(@415 Unsupported media type) 不支撑媒体类型错误,然后经过查阅材料终于解决了。这里总结下关于ajax与后台传输数据的几种方式,上面问题的解决办法在本文最后。


1.把数据放到url中传递
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById/"+id,//参数放在url中
success:function(data){ alert(data);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
后台:

<pre><code>

@RequestMapping(value = "getPeopleById/{id}")
@ResponseBody
    public Map<String, Object> getPeopleById(@PathVariable("id") int id) {
        //@PathVariable("id") 假如参数名与url定义的一样注解可以不消定义("id")
        System.out.println(id);
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }
}

</code></pre>

2.把数据放到data中
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById",
data: {id:id},
success:function(data){ alert(data.result);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
后台(两个方式):

<pre><code>

@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map<String, Object> getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    Map<String, Object> map = new HashMap<String, Object>();
    return map;
}

</code></pre>


@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map<String, Object> getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    // 这里得到的都是字符串得转换成你需要的类型
    Map<String, Object> map = new HashMap<String, Object>();
    return map;
}

</code>

3.以json传输(就是开头说的状况)
js(包括一些常见的ajax参数说明):
<code>
var id = $("#id").val();
$.ajax({
type: "POST",//恳求类型
timeout:10000,  //设定恳求超不时间(毫秒)
async:ture,//可否为异步恳求
cache:false,//可否从阅读器缓存中加载恳求信息。
url: "/IFTree/people/getPeopleById",
contentType: "application/json;charset=UTF-8",//提交的数据类型
data: JSON.stringify({id:id}),//这里是把json转化为字符串情势
dataType: "json",//返回的数据类型
success:function(data){
$("#name").val(data.result.name);
},
error:function(xhr, textStatus, errorThrown) {
}
});
});
</code>
后台:

<pre><code>

@RequestMapping(value = "getPeopleById", produces = "application/json")
@ResponseBody
public Map<String, Object> getPeopleById(@RequestBody Map<String, Object> body){
    System.out.println(""+body.get("id"));
    People people = peopleService.getPeopleById(Integer.valueOf((String)body.get("id")));
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("result", people);
    return map;
}

</code></pre>

详解:

@RequestBody
该注解第一读取request恳求的正文数据,然后使用默许配置的HttpMessageConverter停止解析,把数据绑定要对象上面,然后再把对象绑定到controllor中的参数上。
@ResponseBody
该注解也是一样的用于将Controller的办法返回的对象,通过的HttpMessageConverter转换为指定格局后,写入到Response对象的body数据区。

Srping mvc .xml(配置转换器)

<code>

 <!-- spring MVC供给的适配器 spring默许加载 (假如不修改默许加载的4类转换器,该bean可不配置)-->
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <!-- 该适配器默许加载以下4类转换器-->
        <list>
            <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
            <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
            <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean><!--这里配置了json转换器支撑的媒体类型-->
        </list>
    </property>
</bean>

</code>
ByteArrayHttpMessageConverter: 负责读取二进制格局的数据和写出二进制格局的数据;
StringHttpMessageConverter: 负责读取字符串格局的数据和写出二进制格局的数据;
ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据;
FormHttpMessageConverter: 负责读取form提交的数据
MappingJacksonHttpMessageConverter: 负责读取和写入json格局的数据;
SouceHttpMessageConverter: 负责读取和写入 xml 中javax.xml.transform.Source定义的数据;
Jaxb2RootElementHttpMessageConverter: 负责读取和写入xml 标签格局的数据;
AtomFeedHttpMessageConverter: 负责读取和写入Atom格局的数据;
RssChannelHttpMessageConverter: 负责读取和写入RSS格局的数据;

项目里面我用到的只要json转换器,所以要导入关于json的包(maven):

<code>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
</code>

一样controller中参数也能以实体类的方式接收数据,
开端不断报(415 Unsupported media type)的错误是由于配置文件没有写对也没导入响应的包。
假如有哪里不足或错误的地方望提出,感谢_

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板