在AJAX和Spring中处理对象列表

问题描述 投票:1回答:1

我无法解析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);
    }   

*浏览器输出*访问失败[对象对象]

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个回答
0
投票

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

@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;
    }

© www.soinside.com 2019 - 2024. All rights reserved.