SpringMVC+JS實現Ajax請求返回Json

1. 引入Json依賴

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.5</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.5</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

2. 加入json解析配置

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="messageConverters">
             <list>
                    <ref bean="mappingJackson2HttpMessageConverter" />
             </list>
      </property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
     class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="supportedMediaTypes">
             <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                    <value>text/json;charset=UTF-8</value>
             </list>
      </property>
</bean>

3. 前端請求

<body>
    <h1>數據請求</h1><hr/>
    <input type="text" name="arg1" /><button onclick="arg1Submit()">提交</button>
    <h1>數據響應</h1><hr/>
    返回數據:<span id="res"></span>
</body>
<script>
  function arg1Submit(){
    var arg1Val = document.querySelector("input[name=arg1]").value;
    console.log(arg1Val);
    var json = {"arg1":arg1Val};

    var ajax = new XMLHttpRequest();
    ajax.open("post","/data/query01");
    ajax.setRequestHeader("Content-type","application/json; charset=utf-8");
    ajax.send(JSON.stringify(json));
    ajax.onreadystatechange = function () {
      if (ajax.readyState==4&&ajax.status==200) {
        document.querySelector("#res").innerHTML = ajax.responseText;
      }
    }
  }
</script>

4. 後端響應

@RequestMapping("query01")
@ResponseBody
public String query01(@RequestBody Map<String,Object> map){
    String result = "這個結果是:"+map.get("arg1");
    return result;
}

5. 注意事項

a. 使用@ResponseBody註解出現404,需檢查json依賴與配置是否正確。

b. 使用@RequestBody註解出現400,建議使用JSON.stringify方式傳參。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章