如何在 Java 脚本中访问在 AJAX 请求中作为响应发送的自定义 Java 对象?

How to access custom Java object sent as response in AJAX request, in JavaScript?

我正在开发 Spring MVC 应用程序,我需要在其中显示 Trip 对象的详细信息。以下是我的 TripModel:

@Entity
@Table(name="Trip")
public class TripModel {
    private String locationName;

    private String userName;
    @Id
    @Column(name="tripid")
    @GeneratedValue 
    private int tripId; 

    @Column(name="tripid")
    private int tripId;

    @Column(name="locationid")
    private int tripStopLocationId;

    @Column(name="datetime")
    private String tripStopDateTime;

    @Column(name="createts")
    private Date tripStopCreateTime;

    @Column(name="userid")
    private int createUserId;

    @Transient
    private List<ItemTransactionModel> itemTransactionModelList;
}

如何在 AJAX 中使用行程 ID 获取行程详细信息? TripModel 有一个 ItemTransactionModel 对象列表。

以下是我的 ajax 代码:

jQuery.ajax({
        url: '<c:url value="/trip/tripdetailsbyajax" />',
        type: 'POST',
        data: "tripId="+tripId,
        cache:false,
        success:function(response){
            alert("response = " + response);
        },
        error:function(jqXhr, textStatus, errorThrown){
            alert(jqXhr);
            alert(textStatus);
            alert(errorThrown);
        }
    });

以下是我的控制器方法:

@RequestMapping(value = "/tripdetailsbyajax", method = { RequestMethod.POST })
    public @ResponseBody TripModel getTripDetailsByAjax(int tripId) {
        TripModel tripModel = null;
        tripModel = tripService.getTripModel(tripId);
        return tripModel;
    }

我们如何将 TripModel 对象作为 AJAX 响应发送,以及我们如何在 JavaScript 中访问它? TripModel 对象有一个 ItemTransactionModel 对象列表。

您需要进行一些更改才能获得 JSON、

的回复

dataType:json 添加到您的 ajax 请求中,以便它知道它应该期待来自服务器

jQuery.ajax({
        url: '<c:url value="/trip/tripdetailsbyajax" />',
        type: 'POST',
        dataType: 'json',

在您的处理程序方法的 RequestMapping 中添加一个 produces="application/json"。这将提示框架将响应转换为的表示

@RequestMapping(value = "/tripdetailsbyajax", method = { RequestMethod.POST }, produces="application/json")

最后,访问成功方法中的值,如 response.userName

请注意,确保您的实体具有适当的 getters/setters,负责将您的对象转换为 JSON 的 jackson 库,处理属性