【问题标题】:Spring MVC return simple text instead of JSON while using Ajax CallSpring MVC 在使用 Ajax 调用时返回简单文本而不是 JSON
【发布时间】:2016-08-15 21:05:21
【问题描述】:

这是我的 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。

我得到一个明文作为响应,错误消息是“Unexpected token s”

这是我的服务器端代码:

@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;
    }
}

我做错了什么?

【问题讨论】:

    标签: java jquery json ajax spring


    【解决方案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

    • jackson-annotations-2.6.0.jar
    • jackson-core-2.6.0.jar
    • jackson-databind-2.6.0.jar

    我发现这个link 很有用。

    【讨论】:

    • 问题在于,这仅在我为示例 CommonConfigurations 返回一个类对象时才有效,当我返回一个字符串时,我将其作为纯文本而不是 json 格式获取
    • 我想以 JSON 格式的字符串返回 - "Sandbox" 或 "Production" 的值。
    • 您可以将字符串值格式化为 json,例如 -- return "[{\"ServerType\":\"Production\"}]";
    • @RequestMapping(value = "/serverType") public String getServerType(){ return "[{\"ServerType\":\"Production\"}]"; }
    • 这会将结果返回为 [{"ServerType":"Production"}]
    【解决方案2】:

    您可以从控制器方法返回整个configurations 对象,并在您的ajax 回调中调用data.activePlatform,前提是您的配置对象不是太大而不能说您跨层携带了太多不必要的数据。

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 2014-10-24
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多