【问题标题】:parsererror: Unexpected token r in JSON at position 0解析器错误:位置 0 处的 JSON 中的意外标记 r
【发布时间】:2018-03-27 00:38:59
【问题描述】:

我有一个 spring mvc 应用程序。我正在尝试使用以下方法发送 http post 请求:

$.ajax({
        type: 'POST',
        url: '/suggested-events/vote/'+votedEventId,
        success: function(response) { console.log("Hey: "+JSON.parse(response)); },
        
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           console.log("TextStatus: "+textStatus);
           console.log("ErrorThrown: "+errorThrown);
        },
        contentType: "application/json",
        dataType: 'json'
    });

http post请求成功触发下面的rest控制器方法:

@PostMapping("/suggested-events/vote/{votedEventId}")
    public ResponseEntity<String> voteForASuggestedEvent(@PathVariable Long votedEventId){
        log.info("You have made a vote for: "+votedEventId);
                HttpHeaders responseHeaders = new HttpHeaders();

    return new ResponseEntity<String>("responseHeaders", responseHeaders, HttpStatus.CREATED);

    }

但如您所见,我有兴趣在控制台中接收并打印响应数据:

success: function(data) { console.log("Hey: "+data); }

问题是:我的控制台没有任何反应

我确定后端收到请求并提供答案。

下图显示其余响应到达浏览器控制台中的网络检查

但它不会在控制台中打印出来

【问题讨论】:

  • 所以添加一些错误处理并检查浏览器开发工具网络中的实际请求
  • 是的。添加错误处理程序并检查 ajax 请求

标签: jquery ajax rest spring-mvc


【解决方案1】:

如果contentType设置为application/json,jQuery的ajax会自动解析数据,所以这里不需要解析

console.log("Hey: "+JSON.parse(response));

替换为

console.log("Hey: "+ response);

除此之外,如果您需要 JSON,则需要从控制器返回 JSON...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2017-10-21
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多