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.
<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>
<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; } }
<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>
<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; }
@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> 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></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;
}</pre><div class="contentsignin">Copy after login</div></div><p>
@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.
</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> <!-- 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></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>
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!