You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AJAX调用将数据加载到Kendo Grid?Spring Boot排障

问题:Spring Boot航班Controller无法通过AJAX给Kendo Grid返回数据

我正在开发一个航班预订Spring Boot应用,已定义Controller从数据库获取航班详情:

@Controller
@RequestMapping("/home")
public class FlightController {
    
    @Autowired
    private FlightService flightService;
    
    @GetMapping("/search")
    public String getFlights(
                @RequestParam("origin") String origin,
                @RequestParam("destination") String destination,
                Model model,
                HttpSession session) {
        
        List<Flight> flightList = flightService.getFightsByOriginAndDestination(origin, destination);
        
        if(flightList.isEmpty()) {
             model.addAttribute("message", "No flights available for the given origin and destination.");
             return "home";
        }
        else {
            model.addAttribute("flightList", flightList);
            model.addAttribute("username", session.getAttribute("username"));
            return "home";
        }
    }
}

现在我希望通过AJAX调用将详情展示到Kendo Grid中,但尝试如下代码后未能成功:

$(document).ready(function () {
                
    $.ajax({
        url: "/home/search",
        type: "GET",
        dataType: "local",

        success: function (data) {
                       
            $("#grid").kendoGrid({
                   dataSource: {
                        data: data,
                        pageSize: 10 
                   },
                   height: 550,
                   sortable: true,
                   pageable: true,
                   columns: [
                          { field: "flight_Number", title: "Flight Number" },
                          { field: "airline_Name", title: "Airline Name" },
                          { field: "departure", title: "Departure" },
                          { field: "arrival", title: "Arrival" },
                          { field: "date", title: "Date" },
                          { field: "price", title: "Price" }
                       
                   ]
            });
        },
        error: function (xhr, status, error) {
            console.error("Failed to fetch flight data:", error);
        }
    });
});

我知道存在问题,但无法定位,能否帮忙排查?


问题排查与修复方案

1. Controller返回类型错误,无法提供AJAX需要的JSON数据

当前Controller用@Controller+返回字符串"home"的逻辑是渲染HTML视图,会返回整个页面内容,而非AJAX所需的JSON格式数据。

修复方式:

  • 将@Controller替换为@RestController(或在@GetMapping方法上添加@ResponseBody注解)
  • 修改方法返回值为ResponseEntity,直接返回封装好的JSON数据:
@RestController
@RequestMapping("/home")
public class FlightController {
    
    @Autowired
    private FlightService flightService;
    
    @GetMapping("/search")
    public ResponseEntity<Object> getFlights(
                @RequestParam("origin") String origin,
                @RequestParam("destination") String destination,
                HttpSession session) {
        
        List<Flight> flightList = flightService.getFightsByOriginAndDestination(origin, destination);
        
        if(flightList.isEmpty()) {
             return ResponseEntity.ok(Map.of("message", "No flights available for the given origin and destination."));
        }
        else {
            return ResponseEntity.ok(Map.of(
                "flightList", flightList,
                "username", session.getAttribute("username")
            ));
        }
    }
}

2. AJAX请求参数缺失+dataType配置错误

  • 原AJAX未传递origin和destination参数,Controller的@RequestParam会因参数缺失直接返回400错误
  • dataType: "local"是无效配置,需改为"json",明确告诉jQuery期望接收JSON格式响应

修复后的AJAX代码:

$(document).ready(function () {
    // 从页面输入框获取出发地和目的地(示例:假设输入框id为origin、destination)
    const origin = $("#origin").val();
    const destination = $("#destination").val();
                
    $.ajax({
        url: "/home/search",
        type: "GET",
        dataType: "json",
        data: {
            origin: origin,
            destination: destination
        },
        success: function (response) {
            if (response.flightList && response.flightList.length > 0) {
                $("#grid").kendoGrid({
                    dataSource: {
                        data: response.flightList,
                        pageSize: 10 
                    },
                    height: 550,
                    sortable: true,
                    pageable: true,
                    columns: [
                        { field: "flightNumber", title: "Flight Number" }, // 字段名需与Flight实体类属性完全一致
                        { field: "airlineName", title: "Airline Name" },
                        { field: "departure", title: "Departure" },
                        { field: "arrival", title: "Arrival" },
                        { field: "date", title: "Date" },
                        { field: "price", title: "Price" }
                    ]
                });
            } else {
                console.log(response.message);
                // 可在此处添加无航班提示的页面逻辑
            }
        },
        error: function (xhr, status, error) {
            console.error("Failed to fetch flight data:", error);
            console.log("Response content:", xhr.responseText); // 打印完整响应,方便排查具体错误
        }
    });
});

3. Kendo Grid字段名需与实体类属性严格匹配

Kendo Grid的field值必须和Flight实体类的属性名完全一致,比如实体类用小驼峰flightNumber,就不能写成下划线格式的flight_Number,否则会导致数据无法绑定到列上。

4. 额外排查建议:添加日志

在Controller方法中添加日志,确认参数接收、数据查询是否正常:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/home")
public class FlightController {
    private static final Logger logger = LoggerFactory.getLogger(FlightController.class);
    
    @Autowired
    private FlightService flightService;
    
    @GetMapping("/search")
    public ResponseEntity<Object> getFlights(
                @RequestParam("origin") String origin,
                @RequestParam("destination") String destination,
                HttpSession session) {
        
        logger.info("Received search request: origin={}, destination={}", origin, destination);
        List<Flight> flightList = flightService.getFightsByOriginAndDestination(origin, destination);
        logger.info("Found {} flights", flightList.size());
        
        // 剩余逻辑不变
    }
}

内容的提问来源于stack exchange,提问作者Hisham Gundagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:53:13