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


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

我傳的數據是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>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM