本文提供 ajax 远程请求数据的例子。

 这里首先要知道 JSONP,可以参考:http://hanchaohan.blog.51cto.com/2996417/1291927

前台 发送端:

 1 <html>
 2 <head>
 3     <title>Remote Ajax</title>
 4   <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
 5   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 6   <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 7   
 8   <script>
 9       $(document).ready(function() {
10             $("#remoteAjaxBtn" ).click(function(){
11                  $.ajax({
12                             type: "POST",
13                             data:{employee_ID:"C1011"},
14                             url : "http://这里写你的host IP:8080/MvnSpringMVC/test.do",
15                             dataType : "jsonp",
16                             jsonp: "callback", 
17                             error : function(e,ex){
18                                 alert("error");    
19                             },
20                             success : function(data) {
21                                 alert(data.msg);
22                             }
23                         });
24             })
25       });
26   </script>
27 </head>
28 <body>
29  
30 <div id="draggable" class="ui-widget-content">
31    <button id="remoteAjaxBtn">send ajax</button>
32   
33 </div>
34  
35 </body>
36 </html>

 

后台Controler

 1 package cc.monggo.web.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import org.springframework.stereotype.Controller;
10 import org.springframework.ui.ModelMap;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 
13 @Controller
14 public class testIVO {
15     @RequestMapping("test.do")
16     public void testFnc(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
17             throws ServletException, IOException {
18         String strEmployee_FK = request.getParameter("employee_ID");
19         System.out.println("employee_ID: " + strEmployee_FK);
20         String callback = request.getParameter("callback");
21         response.setContentType("text/javascript");
22         response.setCharacterEncoding("utf-8");
23         response.getWriter().write(callback + "({msg:'success'})");
24     }
25 }

运行结果

 

 

 

posted on 2013-11-15 13:23  遥远的绝响  阅读(210)  评论(0编辑  收藏  举报