2016-04-22 36 views
0

這是我的Ajax調用:Spring MVC的返回簡單的文本,而不是JSON在使用Ajax調用

$.ajax({ 
     url: 'configuration/activePlatform/', 
     type: 'GET', 
     dataType: 'json', 
     contentType: "application/json", 
     success: function(data){ 
      console.log("getActivePlatform ACK"); 
      $('#activePlatform').append(data); 
     },  
     error: function(xhr, status, error) { 
     var err = eval("(" + xhr.responseText + ")"); 
     alert(err.Message); 
     } 
    }); 

從這一呼籲的響應是200 OK。

我得到一個明確的文本作爲輸入反應,錯誤味精是「意外令牌的」

這是我的服務器端代碼:

@Controller 
@RequestMapping("/configuration") 
public class configuration { 

    @Autowired 
    public CommonConfigurations configurations; 


    @RequestMapping(value = "/activePlatform", method = RequestMethod.GET, 
      produces = MediaType.APPLICATION_JSON) 
    public @ResponseBody 
    String activePlatform() throws Exception { 

     return configurations.activePlatform; 
    } 
} 

我做了什麼錯?

回答

1

在您的dispatcher-servlet.xml您需要將viewName「jsonTemplate」配置爲MappingJackson2JsonView類型的bean。您需要配置類型爲BeanNameViewResolver的視圖解析器。這樣,viewName「jsonTemplate」將與MappingJackson2JsonView匹配,並且解析的JSON響應將返回給客戶端。

<mvc:annotation-driven/> 
<bean name="viewResolver" 
class="org.springframework.web.servlet.view.BeanNameViewResolver"/> 
<bean name="jsonTemplate" 
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> 

重要: -

你需要有以下JAR在classpath

  • 傑克遜的註解-2.6.0.jar
  • 傑克遜核心-2.6.0 .jar
  • jackson-databind-2.6.0.jar

我發現這個link有用。

+0

問題是,這只是當我返回一個例子CommonConfigurations類對象,當我返回一個字符串,我把它作爲純文本,而不是在JSON格式 – USer22999299

+0

爲什麼你需要一個字符串消息,你能解釋一下你的問題有點.. –

+0

我想返回的值 - 「沙盒」或「生產」作爲JSON格式的字符串。 – USer22999299

0

您可以從控制器方法返回整個configurations對象,並在你的Ajax回調假設你的配置對象調用data.activePlatform是不是太大了,說你是跨層承載了太多不必要的數據。

相關問題