【问题标题】:Handling a List of Object in AJAX and Spring在 AJAX 和 Spring 中处理对象列表
【发布时间】:2020-04-06 18:15:28
【问题描述】:

我无法解析 AJAX 中的对象列表,每当我尝试解析列表时,ERROR code 406 就会弹出。但是如果我尝试发送一个字符串,它会收到很好的。

控制器代码

@RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
    @ResponseBody
    public List<State> liststates(HttpServletRequest request){
        String country = request.getParameter("country");
        List<State> states = adminService.getAllstates(Integer.parseInt(country));
        System.out.println("The states we recieved is" +states);
        String result ="hello Bhaskar "+ country;
        return states;
    }

JSP AJAX 代码

var id = $('#select_country').val();
$.ajax({
    url : "getstates",
    data: {country : id},
    dataType: 'application/json',
    type: 'POST',
    success : function(response) {
        alert("Access Success "+ response);
        $('#select_country').append("<option value='-1'>Select User</option>");
        for ( var i = 0, len = response.length; i < len; ++i) {
            var user = response[i];
            $('#select_country').append("<option value=\"" + user.id + "\">" + user.state+ "</option>");
    }

    },
    error : function(response) {
        alert("Access Fail "+ response);
    }   

* 浏览器输出* 访问失败 [object Object]

Open Output Image

* 控制台输出*

我们收到的状态是 [in.complit.model.State@7dee7dc6, in.complit.model.State@54263ffc, in.complit.model.State@43e78960, in.complit.model.State@4ce669b5]

【问题讨论】:

标签: ajax spring spring-mvc jsp


【解决方案1】:

通过在 Controller 中调用服务类方法时添加 try-catch 块 解决的问题班级。添加后的代码如下所示。

@RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
    @ResponseBody
    public List<State> liststates(HttpServletRequest request){
        //List<Country> listCountries = adminService.getAllcountries();
        String country = request.getParameter("country");
        List<State> states = new ArrayList<State>();
         try {
                states = adminService.getAllstates(Integer.parseInt(country));
         }catch(Exception e) {
             System.out.println(e);
         }
        System.out.println("The Country We Recieved "+ country);
        System.out.println("The states we recieved is" +states);
        return states;
    }

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 2020-07-13
    • 2016-07-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 2011-08-21
    相关资源
    最近更新 更多