jquery - how to return object from controller to ajax in spring mvc -
i have return list of employee controller jquery ajax. how should it?
//controller part @requestmapping("phcheck") public modelandview pay(@requestparam("empid") int empid, string fdate, string tdate) { modelandview mav = new modelandview("phcheck"); list<employee> emp=entitymanager.createquery("select e employee e e.empid="+empid, employee.class).getresultlist(); mav.addobject("emp", emp); <----i need list of employee in ajax return mav; }
ajax in view
//ajax part $(document).ready(function () { $("#empid").change(function () { if ($("#fdate").val() != "" && $("#tdate").val() != "" && $("#empid").val() != "") { jquery.ajax({ url: "phcheck.htm?empid=" + $("#empid").val() + "&&fdate=" + $("#fdate").val() + "&&tdate=" + $("#tdate").val(), success: function (data) { alert(data + "success"); }, error: function (data) { alert(data + "error"); } }); } else { alert("please fill date , date or select employee id"); $("#empid .option").attr("selected", "selected") } });
});
thanks in advance.
i need list of employee in ajax
in spring when need object serialization, de-serialization , message conversion. in case need annotate controller handler method @requestbody
, @responsebody
.
where:
- @responsebody : inform spring try convert return value , write http response automatically.
- @requestbody : inform spring try convert content of incoming request body parameter object on fly.
in case need json type, have add @responsebody
method signature or above method, , produces , consumes optional, like:
@requestmapping(value="phcheck", method=requestmethod.get produces="application/json") public @responsebody list<employee> pay(@requestparam("empid") int empid, string fdate, string tdate) { //get employee list here return emplist; }
and in ajax call use:
contenttype: 'application/json'
attribute tells type of data you're sending. anddatatype: json
attribute tells jquery content type of response receive.
in case contenttype: 'application/json'
not needed, default 1 i.e. 'application/x-www-form-urlencoded; charset=utf-8'
enough.
and can receive list of employees in ajax success, iterate on like:
success: function (data) { $.each(data, function(index, curremp) { console.log(curremp.name); //to print name of employee }); },
note: jackson mapper or other mapper should available on buildpath in order work json serialize , deserialize.
see also:
Comments
Post a Comment