溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Spring中ajax與后臺(tái)傳輸數(shù)據(jù)的示例

發(fā)布時(shí)間:2020-12-07 10:22:34 來(lái)源:億速云 閱讀:156 作者:小新 欄目:web開(kāi)發(fā)

小編給大家分享一下Spring中ajax與后臺(tái)傳輸數(shù)據(jù)的示例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

最近寫(xiě)ajax與后臺(tái)傳輸數(shù)據(jù)的時(shí)候碰到了一個(gè)問(wèn)題,我想ajax以json的方式把數(shù)據(jù)傳輸個(gè)后臺(tái),后臺(tái)用map的形式接收,然后也以map的形式傳回?cái)?shù)據(jù)??墒且恢迸龅角芭_(tái)報(bào)(*)(@415 Unsupported media type) 不支持媒體類(lèi)型錯(cuò)誤,然后經(jīng)過(guò)查閱資料終于解決了。這里總結(jié)下關(guān)于ajax與后臺(tái)傳輸數(shù)據(jù)的幾種方式,上面問(wèn)題的解決方法在本文最后。


<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById/"+id,//參數(shù)放在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") 如果參數(shù)名與url定義的一樣注解可以不用定義("id")
        System.out.println(id);
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }
}

</code></pre>

<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"));
    // 這里得到的都是字符串得轉(zhuǎn)換成你需要的類(lèi)型
    Map<String, Object> map = new HashMap<String, Object>();
    return map;
}

</code>

<code>
var id = $("#id").val();
$.ajax({
type: "POST",//請(qǐng)求類(lèi)型
timeout:10000,  //設(shè)置請(qǐng)求超時(shí)時(shí)間(毫秒)
async:ture,//是否為異步請(qǐng)求
cache:false,//是否從瀏覽器緩存中加載請(qǐng)求信息。
url: "/IFTree/people/getPeopleById",
contentType: "application/json;charset=UTF-8",//提交的數(shù)據(jù)類(lèi)型
data: JSON.stringify({id:id}),//這里是把json轉(zhuǎn)化為字符串形式
dataType: "json",//返回的數(shù)據(jù)類(lèi)型
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請(qǐng)求的正文數(shù)據(jù),然后使用默認(rèn)配置的HttpMessageConverter進(jìn)行解析,把數(shù)據(jù)綁定要對(duì)象上面,然后再把對(duì)象綁定到controllor中的參數(shù)上。
@ResponseBody
該注解也是一樣的用于將Controller的方法返回的對(duì)象,通過(guò)的HttpMessageConverter轉(zhuǎn)換為指定格式后,寫(xiě)入到Response對(duì)象的body數(shù)據(jù)區(qū)。

<code>

 <!-- spring MVC提供的適配器 spring默認(rèn)加載 (如果不修改默認(rèn)加載的4類(lèi)轉(zhuǎn)換器,該bean可不配置)-->
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <!-- 該適配器默認(rèn)加載以下4類(lèi)轉(zhuǎn)換器-->
        <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轉(zhuǎn)換器支持的媒體類(lèi)型-->
        </list>
    </property>
</bean>

</code>
ByteArrayHttpMessageConverter: 負(fù)責(zé)讀取二進(jìn)制格式的數(shù)據(jù)和寫(xiě)出二進(jìn)制格式的數(shù)據(jù);
StringHttpMessageConverter:   負(fù)責(zé)讀取字符串格式的數(shù)據(jù)和寫(xiě)出二進(jìn)制格式的數(shù)據(jù);
ResourceHttpMessageConverter:負(fù)責(zé)讀取資源文件和寫(xiě)出資源文件數(shù)據(jù);
FormHttpMessageConverter:       負(fù)責(zé)讀取form提交的數(shù)據(jù)
MappingJacksonHttpMessageConverter:  負(fù)責(zé)讀取和寫(xiě)入json格式的數(shù)據(jù);
SouceHttpMessageConverter:                   負(fù)責(zé)讀取和寫(xiě)入 xml 中javax.xml.transform.Source定義的數(shù)據(jù);
Jaxb2RootElementHttpMessageConverter:  負(fù)責(zé)讀取和寫(xiě)入xml 標(biāo)簽格式的數(shù)據(jù);
AtomFeedHttpMessageConverter:              負(fù)責(zé)讀取和寫(xiě)入Atom格式的數(shù)據(jù);
RssChannelHttpMessageConverter:           負(fù)責(zé)讀取和寫(xiě)入RSS格式的數(shù)據(jù);

項(xiàng)目里面我用到的只有json轉(zhuǎn)換器,所以要導(dǎo)入關(guān)于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中參數(shù)也能以實(shí)體類(lèi)的方式接收數(shù)據(jù),
開(kāi)始一直報(bào)(415 Unsupported media type)的錯(cuò)誤是因?yàn)榕渲梦募](méi)有寫(xiě)對(duì)也沒(méi)導(dǎo)入相應(yīng)的包

以上是“Spring中ajax與后臺(tái)傳輸數(shù)據(jù)的示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI