如何从控制器返回对象阿贾克斯Spring MVC中 [英] how to return object from controller to ajax in spring mvc

查看:223
本文介绍了如何从控制器返回对象阿贾克斯Spring MVC中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不从控制器返回的员工列表jQuery的阿贾克斯。我应该怎么办呢?

  //控制器部分
@RequestMapping(phcheck)
公共ModelAndView的工资(@RequestParam(EMPID)INT EMPID,FDATE字符串,字符串tdate){

   ModelAndView的MAV =新的ModelAndView(phcheck);
   名单<员工> EMP = entityManager.createQuery(选择从员工的E E其中,e.empId =+ EMPID,Employee.class).getResultList();
   mav.addObject(EMP,EMP); < ----我需要员工在AJAX这个名单
   返回MAV;
}
 

阿贾克斯查看

  //阿贾克斯的一部分
$(文件)。就绪(函数(){
$(#EMPID)。改变(函数(){
    如果($(#FDATE)VAL()=!&放大器;&安培; $(#tdate)VAL()=!&放大器;&安培; $(#EMPID)VAL( )!=){
        jQuery.ajax({
            网址:phcheck.htm EMPID =?+ $(#EMPID)VAL()+&放大器;&安培; FDATE =+ $(#FDATE)VAL()+&放大器;&安培; tdate。 =+ $(#tdate)。VAL(),
            成功:功能(数据){
                警报(数据+成功);
            },
            错误:功能(数据){
                警报(数据+错误);
            }
        });
    } 其他 {
        警报(请填写的日期和日期或选择员工ID);
        $(#EMPID。​​选项)。ATTR(选择,选择)
    }
});
 

});

在此先感谢。

解决方案
  

我需要员工在AJAX这个名单

在当你需要对象的序列化,反序列化和信息转换春天。在这种情况下,你需要注释你的控制器处理方法与 @RequestBody @ResponseBody

其中:

  • @ResponseBody 的:将通知弹簧尝试转换它的返回值,并将其写入自动HTTP响应
  • @RequestBody 的:将通知弹簧试图传入请求正文的内容转换为您的参数对象的飞行

在你的情况,你需要JSON的类型,你必须添加 @ResponseBody 来你的方法的签名或只是上面的方法,以及生产和消费,哪些是可选,如:

  @RequestMapping(值=phcheck,方法= RequestMethod.GET
                生产=应用/ JSON)
公共@ResponseBody名单,其中,员工>工资(@RequestParam(EMPID)INT EMPID,FDATE字符串,字符串tdate){

  //得到你的员工列表在这里
  返回empList;
}
 

在AJAX调用使用:

  • 的contentType:应用/ JSON的属性告诉数据正在发送的类型。和
  • 数据类型:JSON 属性告诉响应jQuery的哪些内容类型将收到

在你的情况的contentType:应用/ JSON的是不需要的,默认的就是应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8就足够了。

和可以接受的员工名单中的AJAX成功,迭代它不喜欢:

 成功:功能(数据){
          $每个(数据,函数(指数,currEmp){
             执行console.log(currEmp.name); //打印员工名字
         });
        },
 


注意:杰克逊映射或其他任何映射器应该是可以在构建路径,为了工作的JSON序列化和反序列化。

另请参见:

I have to return the list of employee from Controller to jQuery ajax. How should I do for 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 from Employee e where e.empId="+empid, Employee.class).getResultList();
   mav.addObject("emp", emp); <----I need this 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 the from date and to date or select the employee id");
        $("#empid .option").attr("selected", "selected")
    }
});

});

Thanks in advance.

解决方案

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:

这篇关于如何从控制器返回对象阿贾克斯Spring MVC中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆