2016-11-14 81 views
2

我想從我的控制器string response但我得到下面的錯誤:爪哇 - 字符串@ResponseBody - 錯誤200

SyntaxError: Unexpected end of JSON input(…) "Error 200"

當我變成一個布爾值或不同類型的反應,這是工作正常。問題是當我嘗試返回一個字符串。

JS代碼:

$.ajax({ 
    method: "POST", 
    url: "./signup", 
    data: _data, 
    dataType: "json", 
    contentType : "application/json;charset=UTF-8", 
    success : function(data) { 
     console.log(data) 
    }, 
    error : function(qXHR, textStatus, errorThrown){ 
     console.log(errorThrown, "Error " + qXHR.status); 
    } 
    }); 

控制器代碼:

@RequestMapping(value = "/signup", method = RequestMethod.POST, produces = {"text/plain", "application/*"}) 
    public @ResponseBody String signup(@RequestBody UserSignup details) { 
     //... 
     return message; 
    } 

任何想法我怎麼能解決這個問題?我已經嘗試了一些東西,但沒有任何工作。我認爲響應格式是錯誤的,因爲代碼的期望。

編輯

我已經改變了我的代碼(刪除produces),但我仍然得到同樣的錯誤:

SyntaxError: Unexpected end of JSON input(…) "Error 200"

@RequestMapping(value = "/signup", method = RequestMethod.POST) 
    public @ResponseBody String signup(@RequestBody UserSignup details) { 
     message = "ok"; 
     } 
     return message; 
    } 

回答

0

由於我沒有問題,當迴應是不同的東西作爲String我已經解決了創建我自己的對象的問題。所以,下面是代碼:

public class Response<T> { 
    private T message; 
    private Exception ex; 

    public Exception getEx() { 
     return ex; 
    } 

    public void setEx(Exception ex) { 
     this.ex = ex; 
    } 

    public T getMessage() { 
     return message; 
    } 

    public void setMessage(T message) { 
     this.message = message; 
    } 
} 


@Controller 
public class MyControllerController { 
    private Response<String> _response; 
    private String message; 

    public MyController() { _response = new Response<>(); } 

@RequestMapping(value = "/signup", method = RequestMethod.POST) 
    public @ResponseBody Response<String> signup(@RequestBody UserSignup details) { 
     try{ 
      message = ""; 
      // code... 
      _response.setMessage(message); 
      return _response; 
     }catch (Exception ex){ 
      _response.setEx(ex); 
      return _response; 
     } 
    } 
} 

響應例如在瀏覽器中:

Object {message: "", ex: null}

5

你的方法是錯誤的。您正在說生產產生= {「text/plain」,「application/*」}但是您還添加了將生成JSON格式響應的@ResponseBody。

我建議你刪除屬性生成。並確認你正在返回的字符串以及形成

+0

我曾試圖消除''produces'',我試圖返回一個字符串,如「OK」和我仍然得到相同的錯誤。 @cralfaro – gon250

+0

@ gon250你能否用你正在測試的數據更新你的問題?和錯誤消息?只是爲了與您同時更新 – cralfaro

+0

我已經添加了新的代碼。基本上我已經刪除了產品,並確保我返回一個字符串。 – gon250

0

嘗試包在ResponseEntity類的響應

@RequestMapping(value = "/signup", method = RequestMethod.POST) 
    public @ResponseBody ResponseEntity<String> signup(@RequestBody UserSignup details) { 
     message = "ok"; 
     return new ResponseEntity<>(message, HttpStatus.OK); 
    } 

而且您要發送到服務器仔細檢查數據,也許這就是問題,你能不能告訴我們_data值?