Home > Web Front-end > JS Tutorial > body text

Introducing several methods of ajax and background data transmission in Spring

coldplay.xixi
Release: 2020-12-04 16:27:51
forward
7801 people have browsed it

ajaxThe column introduces the method of transmitting data with the background

Introducing several methods of ajax and background data transmission in Spring

Recommended (free): ajax

I recently encountered a problem when writing ajax and transmitting data to the background. I want ajax to transmit the data to the background in the form of json, and the background will receive it in the form of map, and then return the data in the form of map. . However, I kept encountering the error message (*) (@415 Unsupported media type) at the front desk, and then I finally solved it after consulting the information. Here is a summary of several ways to transmit data between ajax and the background. The solutions to the above problems are at the end of this article.


1. Put the data in the url and pass it
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>
Copy after login
Backend:

<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;
    }
}
Copy after login

2. Put the data into 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>
Copy after login
Backend (two methods ):

<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;
}
Copy after login


@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;
}
Copy after login

3. Transmit with json (the situation mentioned at the beginning)
js (including some common ajax parameter explanations):
<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>
Copy after login
Backend:

< pre></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@RequestMapping(value = &quot;getPeopleById&quot;, produces = &quot;application/json&quot;) @ResponseBody public Map&lt;String, Object&gt; getPeopleById(@RequestBody Map&lt;String, Object&gt; body){ System.out.println(&quot;&quot;+body.get(&quot;id&quot;)); People people = peopleService.getPeopleById(Integer.valueOf((String)body.get(&quot;id&quot;))); Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;(); map.put(&quot;result&quot;, people); return map; }</pre><div class="contentsignin">Copy after login</div></div><p>

Detailed explanation:

@RequestBody
This annotation first reads the request request Text data, then use the default configured HttpMessageConverter to parse, bind the data to the object, and then bind the object to the parameters in the controller.
@ResponseBody
This annotation is also used to convert the object returned by the Controller method into the specified format through HttpMessageConverter, and then writes it to the body data area of ​​the Response object.

Srping mvc .xml (configuration converter)

</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">Copy after login</div></div><p>
ByteArrayHttpMessageConverter: Responsible for reading Get data in binary format and write data in binary format;
StringHttpMessageConverter: Responsible for reading data in string format and writing data in binary format;
ResourceHttpMessageConverter : Responsible for reading resource files and writing resource file data;
FormHttpMessageConverter: Responsible for reading data submitted by form
MappingJacksonHttpMessageConverter: Responsible for reading and writing json format Data;
SouceHttpMessageConverter: Responsible for reading and writing data defined by javax.xml.transform.Source in xml;
Jaxb2RootElementHttpMessageConverter: Responsible for reading and writing Data in xml tag format;
AtomFeedHttpMessageConverter: Responsible for reading and writing data in Atom format;
RssChannelHttpMessageConverter: Responsible for reading and writing data in RSS format;

I only use the json converter in the project, so I need to import the json package (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>
Copy after login

Similarly, the parameters in the controller can also be received in the form of entity classes. Data,
started reporting errors (415 Unsupported media type) because the configuration file was not written correctly and the corresponding package was not imported.
If there are any deficiencies or errors, please point them out, thank you _

If you want to learn more about programming, please pay attention to the php training column !

The above is the detailed content of Introducing several methods of ajax and background data transmission in Spring. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jianshu.com
Previous article:The building blocks of JavaScript Web Workers and 5 usage scenarios Next article:Learn more about modules, import and export in JavaScript
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template