当前位置: 代码迷 >> java >> 页面加载后异步AJAX返回
  详细解决方案

页面加载后异步AJAX返回

热度:83   发布时间:2023-07-26 14:03:38.0

我正在使用Spring MVC,当JSP页面完全加载时,我只需要对服务器进行一次异步调用。

我实际拥有的是一个返回List的Controller。 我使用AJAX调用Controller。 我的解决方案的问题是我无法在加载JSP页面后获取List的数据。

@RequestMapping(method=RequestMethod.GET, value="/myList")
public ModelAndView getSubView(Model model) 
{
  model.addAttribute("list", userServiceI.getAllUsers());
  return new ModelAndView( "myList" );
}
<script type="text/javascript">
  function ajaxPost() {
    $.ajax({
      type: "GET",
      url: "myList",
      success: function(list) {
        alert(list.get(0).name);
      }
    });
  }
</script>

有没有办法返回List After Page加载或如何异步加载? 提前致谢。

只需返回List of User而不是ModelAndView,并在List对象@ResponseBody上给出注释。 用户应该是Serializable,您可以在wiondwos.onload或document.ready上调用ajax函数。它将异步加载列表。不返回ModelAndAiew,它用于在表单提交的情况下重定向页面。

You need to return Json you can try it as follows 

@RequestMapping(method=RequestMethod.GET, value="/myList")
public String getSubView(Model model) 
{
   JSONObject json = new JSONObject();
   return json.put("list", userServiceI.getAllUsers());  
}

or you can use @ResponseBody as 

@RequestMapping(method=RequestMethod.GET, value="/myList")
@ResponseBody
public ArrayList getSubView(Model model) 
{
  return userServiceI.getAllUsers();
}
  相关解决方案