如何使用model作为参数创建ajax成功方法

时间:2016-01-06 10:23:21

标签: javascript jsp

我将选定的客户名从ui发送到后端..该方法返回模型。如何在Ui中处理模型对象。

这是我的代码。

<form:form method="get" action="retrieve" modelAttribute="customer" commandName="customer">
  <b>Environment:</b>
  <form:select path="EnvrironmentId" id="environmentDetails">
    <option selected="selected">Select An Environment</option>
    <form:options items="${map.environmentnamesList}" itemLabel="environmentName" itemValue="envrironmentId"/>
  </form:select>

像这样的事情

<script>
$(document).ready(function() {
    $("#customerDetails").change(function() {
        var value1 = $('#customerDetails :selected').text();
        $.ajax({
            type: 'POST',
            url: 'environments',
            data: {
                selectedcustomername: value1
            },
            success: function(data) {

            }

        });
    });
});



@RequestMapping(value = "/environments", method = RequestMethod.POST)
public ModelAndView getenvironments(HttpServletRequest request,
    HttpServletResponse response, @ModelAttribute("customer") Customer customer, @RequestParam String selectedcustomername) throws Exception {
    System.out.println("selected cust name" + selectedcustomername);
    ModelAndView model = null;
    Map < String, Object > map = new HashMap < String, Object > ();
    List < org.mvc.domain.Environments > environmentnamesList = loginDelegate.getEnvironments(selectedcustomername);
    Collections.sort(environmentnamesList, new CustomComparator());
    for (int i = 0; i < environmentnamesList.size() - 1; i++) {
        customer.setEnvrironmentId(environmentnamesList.get(0));
        customer.setEnvironmentName(environmentnamesList.get(1));
    }
    map.put("environmentnamesList", environmentnamesList);
    model = new ModelAndView("welcome", "map", map);
    return model;

}

我在firebug html部分得到下拉值。但是我无法在主html中加载相同的值..

1 个答案:

答案 0 :(得分:0)

当您从ui发送ajax请求时,它不知道后端的模型,最好的方法是将响应转换为jsonhtml并在您的javascript中使用它。

其他解决方案是从后端本身渲染页面,并在jsp

中添加类似的内容
<script>
  var model=[];
  model.someparam="${model.someparam}";
  model.anotherparam="${model.anotherparam}";
</script>

在js中你可以这样做

alert(model.someparam)