【问题标题】:Using ajax with Spring MVC在 Spring MVC 中使用 ajax
【发布时间】:2011-12-04 19:01:30
【问题描述】:

我目前正在使用 Spring MVC,并且正在尝试使用 ajax 做一些事情。基本上我现在想做的是在网页上动态显示控制器的结果。

I.E.用户按下一个按钮,它会转到“whatever.do”控制器并获取一个列表并显示该列表,而无需重新加载该页面。

有没有人知道任何好的教程或示例项目?

【问题讨论】:

    标签: java javascript spring jsp spring-mvc


    【解决方案1】:

    非常简单,我什至认为不需要专门的教程(除了通用的 spring-mvc 教程)。

    1. 创建一个返回List<Foo>@RequestMapping("/foo") 方法
    2. 在您的 dispatcher-servlet.xml 中添加 <mvc:annotation-driven /> 以激活处理程序映射和转换器
    3. 将 Jackson(json 序列化程序)放在您的类路径中
    4. 使用$.getJSON("/foo", function(data) {..}); (jquery) - 您将获得Foo 对象的 JSON 编码列表

    Spring 将检测到浏览器请求 json 响应,并使用 Jackson 转换您的对象。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 虽然这在理论上可以回答问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
      【解决方案3】:

      当您使用 spring 和 ajax 时,您的控制器必须具有以下格式:

      @RequestMapping(value = "/show.ajax", method = RequestMethod.POST)
      public @ResponseBody List<your object type> your_method_name() {
      
           //code logic
      
      return list_of_your_object;
      }
      

      还有你在jsp页面上的java脚本代码,格式如下:

      <script>
          function your_javascript_fun_name() {
                  $.ajax({
                      type : 'POST',
                      url : 'show.ajax',//this is url mapping for controller
                      success : function(response) {
                          alert(response);
                                       //this response is list of object commming from server
                      },
                      error : function() {
                          alert("opps error occured");
                      }
                  });
              }
      </script>
      

      在jsp页面中导入jquery库

      <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
      

      【讨论】:

        【解决方案4】:
        var id = $("#id").val();
                            var resourceURL = $("#contextpath").val()+"/customer/retrivebyid/"+id;
                            $.ajax({
                                url : resourceURL,
                                type : 'GET',
                                dataType : 'json',
                                async : false,
                                success: function(data) {
                                    var successflag = data.response.successflag;
                                    var errors = data.response.errors;
                                    var results = data.response.result;
                                    if(successflag == "true"){
                                        $.each(results, function (i, result) {
                                            $("#id").val((result.id == undefined || result.id == null || result.id.length <= 0) ? "-" : result.id);
                                            $("#name").val((result.customername == undefined || result.customername == null || result.customername.length <= 0) ? "-" : result.customername);
                                        }); 
                                    }else{
                                        $("#errorMsgContent").html(errors);
                                        $.fancybox.open('#errorMsg');
                                    }
                                },
                                error: function (xhr, ajaxOptions, thrownError) {
                                    $("#errorMsgContent").html(thrownError);
                                    $.fancybox.open('#errorMsg');
                                }
                            });
        

        【讨论】:

        • 请尝试对您的解决方案进行一些解释。仅代码的答案不如那些解释正在发生的事情有用。
        【解决方案5】:
        @RequestMapping(value = "/retrivebyid/{id}", method = RequestMethod.GET)
            public @ResponseBody String retriveUser(@PathVariable long id, Model model,HttpServletRequest request) {
                String jsonresp = null;
                try {
                    List<CustomerDO> customerList = new CustomerService().retriveById(id);
                    jsonresp = CustomerUtil.getCustomerList(customerList).toString();
                } catch (Exception e) {}
        
                if (jsonresp != null) {
                    return jsonresp.toString();
                } else {
                    return null;
                }
            }
        
            public static JSONObject getCustomerList(List<CustomerDO> empList)throws AppException {
                JSONObject responseJSON = new JSONObject();
                JSONObject resultJSON = new JSONObject();
                try {
                    resultJSON.put(CommonConstants.SUCCESS_FLAG, CommonConstants.TRUE);
                    resultJSON.put(CommonConstants.ERRORS, "");
                    JSONArray resultJSONArray = new JSONArray();
                    for (CustomerDO customer : empList) {
                        resultJSONArray.put(getCustomerDetailObject(customer));
                    }
                    resultJSON.put(CommonConstants.RESULTS, resultJSONArray);
                    responseJSON.put(CommonConstants.RESPONSE, resultJSON);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return responseJSON;
            }
        
            private static JSONObject getCustomerDetailObject(CustomerDO customer)throws JSONException, AppException {
                JSONObject result = new JSONObject();
                result.put(CommonConstants.ID, String.valueOf(customer.getId()));
                result.put(CommonConstants.CUSTOMER_NAME, String.valueOf(customer.getName()));
                return result;
            }
        

        【讨论】:

          猜你喜欢
          • 2013-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多