Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

jquery - How to return an object from a Spring MVC controller in response to AJAX request?

I have to return a list of employees from a controller in response to jQuery AJAX request. How should I do for it?

My controller:

@RequestMapping("phcheck")
public ModelAndView pay(@RequestParam("empid") int empid, String fdate, String tdate) {
    ModelAndView mav = new ModelAndView("phcheck");
    List<Employee> employees = entityManager.createQuery(
        "SELECT e FROM Employee e WHERE e.empId = " + empid, Employee.class)
        .getResultList();
    mav.addObject("employees", employees); // I need this list of employee in AJAX

    return mav;
}


AJAX code in the related view:

$(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 the from date and to date or select the employee id");
            $("#empid .option").attr("selected", "selected");
        }
    });
});


Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I need this list of employee in ajax

In spring when you need object serialization, de-serialization and message conversion. in that case you need to annotate your controller handler method with @RequestBody and @ResponseBody.

Where:

  • @ResponseBody : will inform spring that try to convert its return value and write it to the http response automatically.
  • @RequestBody : will inform spring that try to convert the content of the incoming request body to your parameter object on the fly.

in your case you need JSON type, you have to add @ResponseBody to your method signature or just above the method, and produces and consumes which are 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 your employee list here
  return empList;
}

and in AJAX call use:

  • contentType: 'application/json' attribute tells the type of data you're sending. and
  • dataType: json attribute tells jquery what content type of response will receive.

in your case contentType: 'application/json' is not needed, default one i.e. 'application/x-www-form-urlencoded; charset=UTF-8' is enough.

and you can receive list of employees in your AJAX success, to iterate over it do like:

  success: function (data) {
          $.each(data, function(index, currEmp) {
             console.log(currEmp.name); //to print name of employee
         });    
        },


Note: Jackson mapper or any other mapper should be available on buildpath in order to work JSON serialize and deserialize.

See Also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...