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

coldplay.xixi
Lepaskan: 2020-12-04 16:27:51
ke hadapan
7742 orang telah melayarinya

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

介绍Spring中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>
Salin selepas log masuk
后台:

<code></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@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;
    }
}
Salin selepas log masuk

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>
Salin selepas log masuk
后台(两个方式):

<code></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@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;
}
Salin selepas log masuk


@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;
}
Salin selepas log masuk

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>
Salin selepas log masuk
后台:

<code></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@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;
}
Salin selepas log masuk

详解:

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

Srping mvc .xml(配置转换器)

</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> &lt;!-- spring MVC提供的适配器 spring默认加载 (如果不修改默认加载的4类转换器,该bean可不配置)--&gt; &lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot;&gt; &lt;property name=&quot;messageConverters&quot;&gt; &lt;!-- 该适配器默认加载以下4类转换器--&gt; &lt;list&gt; &lt;bean class=&quot;org.springframework.http.converter.BufferedImageHttpMessageConverter&quot; /&gt; &lt;bean class=&quot;org.springframework.http.converter.ByteArrayHttpMessageConverter&quot; /&gt; &lt;bean class=&quot;org.springframework.http.converter.xml.SourceHttpMessageConverter&quot; /&gt; &lt;bean class=&quot;org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter&quot; /&gt; &lt;bean class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot; /&gt; &lt;bean class=&quot;org.springframework.http.converter.json.MappingJacksonHttpMessageConverter&quot;&gt; &lt;property name=&quot;supportedMediaTypes&quot;&gt; &lt;list&gt; &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt;&lt;!--这里配置了json转换器支持的媒体类型--&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt;</pre><div class="contentsignin">Salin selepas log masuk</div></div><p>
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>
Salin selepas log masuk

同样controller中参数也能以实体类的方式接收数据,
开始一直报(415 Unsupported media type)的错误是因为配置文件没有写对也没导入相应的包。
如果有哪里不足或错误的地方望提出,谢谢_

想了解更多编程学习,敬请关注php培训栏目!

Atas ialah kandungan terperinci 介绍Spring中ajax与后台传输数据的几种方式. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:jianshu.com
Artikel sebelumnya:JavaScript Web Workers的构建块及5个使用场景 Artikel seterusnya:详细了解javascript中的modules、import和export
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Isu terkini
Topik-topik yang berkaitan
Lagi>
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!