XMLHttpRequest 跨域访问

案例:ajax请求springMVC controller,跨域访问了要设置response.addHeader("Access-Control-Allow-Origin","*") ;

否则非IE浏览器会显示报错,或者前端页面收不到数据

 

代码如下:

@RequestMapping("/login.do")
 public void login(@ModelAttribute WwUser wwUser,
   HttpServletRequest request,HttpServletResponse response) throws Exception {
  response.addHeader("Access-Control-Allow-Origin","*") ;
  System.out.println("name="+wwUser.getWwUserName());
  System.out.println("password="+wwUser.getWwUserPassword());
  response.setContentType("text/html;charset=utf-8");
  System.out.println("------------------------");

  /*// 验证码
  if (!rand.equals(request.getSession().getAttribute("rand"))) {
   return "vfail";
  }*/

  // 验证用户名,密码
  
  WwUser reUser = wwUserService.login(wwUser,request.getSession().getId());
  if (reUser != null) {
   request.getSession().setAttribute("wwUser", reUser);
   //return "redirect:/manager/frame/account/account_list.jsp";
   //response.getWriter().write("success");
  // return "redirect:/manager/frame/account/account_list.jsp";
   
  // return "success";
   response.getWriter().write("success");
   
  } else {
   //return "forward:/manager/frame/account/account_list.jsp";
  // return "upfail";
   response.getWriter().write("fail");
  }
  
 }

 

-----------------------------------------------------------------------------------------------------------------------

 $(function(){
                $("#login").click(function(){
                   $.post("http://192.168.1.111:8080/BaseWeb/login.do", {
                        wwUserName: $("#username").val(),
                        wwUserPassword: $("#password").val()
                    }, function(backData){
      alert(backData)
                        if(backData=="success"){
       window.location.href='main.html';
      }
                    });
                });
               
            });

你可能感兴趣的:(J2EE)