首頁 > web前端 > js教程 > 主體

介紹Spring中ajax與後台傳輸資料的幾種方式

coldplay.xixi
發布: 2020-12-04 16:27:51
轉載
7742 人瀏覽過

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>
登入後複製
後台:

<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;
    }
}
登入後複製

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>
登入後複製
後台(兩個方式):

<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;
}
登入後複製

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></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">登入後複製</div></div><p>

詳解:

@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">登入後複製</div></div><p>
ByteArrayHttpMessageConverter: 負責讀取取二進位格式的資料和寫出二進位格式的資料;
StringHttpMessageConverter:   負責讀取字串格式的資料和寫出二進位格式的資料;
ResourceHttpMessageConverter :負責讀取資源檔案和寫出資源檔案資料;
FormHttpMessageConverter:       負責讀取form提交的資料
MappingJacksonHttpMessageConverter:  格式在讀取和寫入jsonpingJacksonHttpMessageConverter
:  格式的資料;SouceHttpMessageConverter
:                   負責讀取與寫入xml 中javax.xml.transform.Source定義的資料;##Jb2Root#Jaxb2Root. xml 標籤格式的資料;
AtomFeedHttpMessageConverter:              負責讀取與寫入Atom格式的資料;
RssChannelHttpMessageConverter 專案裡面我用到的只有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)的錯誤是因為設定檔沒有寫對也沒導入相應的包。

如果有哪裡不足或錯誤的地方望提出,謝謝
_

想了解更多程式設計學習,請關注
php培訓

欄目!
#

以上是介紹Spring中ajax與後台傳輸資料的幾種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:jianshu.com
上一篇:JavaScript Web Workers的建構塊及5個使用場景 下一篇:詳細了解javascript中的modules、import和export
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
相關專題
更多>
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!