【问题标题】:Spring Boot Ajax Parse Error - cannot return object to ajax success fnSpring Boot Ajax 解析错误 - 无法将对象返回到 ajax 成功 fn
【发布时间】:2020-10-15 09:09:31
【问题描述】:

我通过 jquery ajax 调用向我的 spring 控制器发送一个值。我希望它发回一个对象以填充 iziModal 中的表单。目前,它将值从浏览器发送回我的控制器,并在我的控制器中运行我的方法,但后来我卡住了。出于某种原因,我在将响应发送回我的 ajax 成功函数时遇到问题。 我收到此解析错误:SyntaxError: Unexpected token t in JSON at position 1556482

这是我的控制器方法:

 @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST)
 public @ResponseBody CarrierAppointment getCarrierDets (@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
       CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
        model.addAttribute("carrierToEdit", carrierToEdit);
        return carrierToEdit;
    }

Ajax 调用:

            $('.trigger-edit-carrier').on('click', function(event){
                var selectId = $(this).attr('value');
                console.log(selectId);
                var token = $("meta[name='_csrf']").attr("content");
                console.log(token);
                var header = "X-CSRF-TOKEN";
                  console.log(header);
                 $.ajax({
                    type: "POST",
                    url: "/editCarrierAjax",
                    data: {data:selectId},
                    dataType:"json",
                    cache: false,
                    timeout: 600000,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader(header, token);
                        console.log(header +", "+ token);
                    },
                    success: function(data, jqXHR){
                          console.log("success fn");
                          console.log(data);
                      
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("Status: " + textStatus); alert("Error: " + errorThrown);
                    }
                });
            });

我已尝试添加此处提到的 Jackson 库 Convert a object into JSON in REST service by Spring MVC

但它仍然会引发错误。知道如何解决此错误吗?

【问题讨论】:

  • 您的 ajax 代码没有 dataType: "json" ?您是否返回 json 响应?
  • @Swati 如果我将 contentType 和 dataType 添加为 json,则会收到 400 错误请求错误。我只是想返回一个对象。我之前在不同的项目中使用过类似的 ajax/代码,它在那里工作,所以不确定这里有什么不好。
  • 目前在您的代码中,您还没有将 carrierToEdit 转换为 json,因为您的 ajax 正在接受 json ?你能用那个更新你的代码吗?然后检查console.log(data); 显示什么?

标签: json ajax spring-boot izimodal


【解决方案1】:

如果您在 jQuery 代码中将 contentType 和 dataType 设置为 json(也许可以试试 application/json!),则返回 400 错误请求状态代码这一事实可能与控制器配置错误有关。如果您的所有控制器方法都处理 JSON(在 requestbody 中接收 JSON 有效负载,在 responsebody 中使用 JSON 有效负载进行响应),那么您可以尝试在您的控制器类级别设置 @RestController 注释 - 此注释还隐式添加 @ResponseBody 注释并配置所有控制器方法以使用和生成application/json 类型的内容。例如。像这样:

@RestController
public class YourControllerClass {

  @PostMapping("/editCarrierAjax")
  public CarrierAppointment getCarrierDets(@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception {
     CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
     model.addAttribute("carrierToEdit", carrierToEdit);
     return carrierToEdit;
  }
}

另一个选项是显式配置这个单一控制器方法,以使用/生成 JSON,例如像这样:

@Controller
public class YourControllerClass {

  @ResponseBody 
  @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public CarrierAppointment getCarrierDets(@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
    CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
    model.addAttribute("carrierToEdit", carrierToEdit);
    return carrierToEdit;
  }
}

如果其中任何一种方法都不能解决您的问题,请分享您的整个控制器和 CarrierAppointment 类。您还应该按照@Programmer 的建议验证发送回您的客户端的生成的 JSON。祝你好运!

【讨论】:

    【解决方案2】:

    您的方法返回的数据似乎在解析 JSON 时出现问题。有时它是由于数据中的一些特殊字符而发生的。您可以尝试记录carrierToEdit(System.out.println(carrierToEdit); ) 在服务器端看看它的价值?可能它会是非常大的字符串内容,并且 id 你把它放在任何文本编辑器中并转到位置 1556482 你会看到导致这种情况的 t...

    SyntaxError: 位置 1556482 处 JSON 中的意外标记 t

    如果您的数据不敏感,您可以尝试使用一些 JSON 验证器工具在线验证它,例如 https://jsonlint.com/

    您可以在那里找到问题,数据/代码中的一些细微更改将解决您的解析问题...

         @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST)
         public @ResponseBody CarrierAppointment getCarrierDets (@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
               CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
    System.out.println(carrierToEdit);
    
                model.addAttribute("carrierToEdit", carrierToEdit);
                return carrierToEdit;
            }

    希望这会有所帮助...一切顺利:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2023-03-24
      • 2011-11-24
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多