我无法解析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);
}
*浏览器输出*访问失败[对象对象]
*控制台输出*
我们收到的状态为[in.complit.model.State @ 7dee7dc6,in.complit.model.State @ 54263ffc,in.complit.model.State @ 43e78960,in.complit.model.State @ 4ce669b5]
通过在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;
}