1. 程式人生 > >$.ajax數據傳輸成功卻執行失敗的回調函數

$.ajax數據傳輸成功卻執行失敗的回調函數

對象 除了 後臺 async fas boolean abi tab body

這個問題迷惑了我好幾天,都快要放棄了,功夫不負有心人,最終成功解決,下面寫一下我的解決方法。

我傳的數據是json類型的,執行失敗的回調函數是因為從後臺傳過來的數據不是嚴格的json類型,所以才會不執行成功的回調函數。

下面貼一下我的代碼

Controller

 @RequestMapping(value="/reg")
    @ResponseBody
    public Map<String,Object> Register(User user) throws IOException{
        Map<String,Object> map = new HashMap<
String,Object>(); boolean isSuccess = userService.Register(user); if(isSuccess){ map.put("tip", "success"); } else{ map.put("tip", "error"); } return map; }

jsp


$.ajax({
type:‘POST‘,
data: {"email":email,"password":password,"type":type},
url:‘user/reg‘,
async:false,
dataType: ‘json‘,
success:function(response){
alert(response.tip);
$(form).find(":submit").attr("disabled", false);
},
error:function(response){
alert(response.tip);
$(form).find(":submit").attr("disabled", false);
}
});


註意我使用了註解@ResponseBody,該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response對象的body數據區。

返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用;

要想使用@ResponseBody需要在配置文件中啟用註解,下面是啟用註解的代碼

  <!--開啟註解-->
    <mvc:annotation-driven />

SpringMVC中使用@ResponseBody註解標註業務方法,將業務方法的返回值做成json輸出給頁面

除了一些spring的包之外,還需要jackson-annotations.jar , jackson-core.jar , jackson-databind.jar 這三個包

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.5.4</version>
        </dependency>

$.ajax數據傳輸成功卻執行失敗的回調函數