解决html跨域请求——JSONP+AJAX+JAVA Servlet



前端:

[html]  view plain  copy
  1. $.ajax({  
  2.     type:"GET",  
  3.     url:"http://127.0.0.1:8020/WALLE/servlet/HomePageAPP",  
  4.     crossDomain: true,  
  5.     data:{  
  6.           
  7.         flag:1//注册  
  8.           
  9.     },  
  10.     dataType:'JSONP',  
  11.     jsonp:"callback",  
  12.     async:true,  
  13.     success:function(data){  
  14.         alert(data.res);  
  15.         var s =JSON.stringify(data);  
  16.         alert(s);  
  17.     }  
  18. });  

后端 Servlet:

[java]  view plain  copy
  1. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.   
  4.     this.doPost(request, response);  
  5. }  
  6.   
  7.   
  8. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  9.         throws ServletException, IOException {  
  10.           
  11.       
  12.      String flag = request.getParameter("flag");  
  13.      String callback = request.getParameter("callback");    
  14.      PrintWriter out = response.getWriter();  
  15.      JSONObject jsonRes =  new JSONObject();  
  16.   
  17.      switch(flag){  
  18.      case "1":  
  19.          jsonRes.put("res""你好呀");  
  20.          String res= callback+"("+jsonRes.toString()+")";  
  21.          out.print(res);  
  22.          out.close();  
  23.      }  
  24.       
  25. }  

前端:

[html]  view plain  copy
  1. $.ajax({  
  2.     type:"GET",  
  3.     url:"http://127.0.0.1:8020/WALLE/servlet/HomePageAPP",  
  4.     crossDomain: true,  
  5.     data:{  
  6.           
  7.         flag:1//注册  
  8.           
  9.     },  
  10.     dataType:'JSONP',  
  11.     jsonp:"callback",  
  12.     async:true,  
  13.     success:function(data){  
  14.         alert(data.res);  
  15.         var s =JSON.stringify(data);  
  16.         alert(s);  
  17.     }  
  18. });  

后端 Servlet:

[java]  view plain  copy
  1. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.   
  4.     this.doPost(request, response);  
  5. }  
  6.   
  7.   
  8. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  9.         throws ServletException, IOException {  
  10.           
  11.       
  12.      String flag = request.getParameter("flag");  
  13.      String callback = request.getParameter("callback");    
  14.      PrintWriter out = response.getWriter();  
  15.      JSONObject jsonRes =  new JSONObject();  
  16.   
  17.      switch(flag){  
  18.      case "1":  
  19.          jsonRes.put("res""你好呀");  
  20.          String res= callback+"("+jsonRes.toString()+")";  
  21.          out.print(res);  
  22.          out.close();  
  23.      }  
  24.       
  25. }  

猜你喜欢

转载自blog.csdn.net/yulei2008_/article/details/79161433
今日推荐