ajax跨域请求--jsonp实例

ajax请求代码:

 

[javascript]  view plain copy
 
  1. //区域事件选择配送点  
  2. function changeDistrict(value){  
  3.      if(value == 0){  
  4.          $('#transport_node').empty();  
  5.          $('#transport_node').append('<option value="0">请选择</option>');  
  6.          return;  
  7.      }  
  8.      $('#transport_node').empty();  
  9.      $('#transport_node').append('<option value="0">加载中...</option>');  
  10.      $.ajax({  
  11.          type: 'GET',  
  12.          url: "http://192.168.33.114:8080/UIDTraceAdmin/transportnode/pagelist/jsonp?callbackFunction=jsonpCallback",  
  13.          async: false,  
  14.          dataType: "jsonp",  
  15.          jsonp: "jsonpCallback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)  
  16.          success: function(o){},  
  17.          timeout:3000    
  18.      });  
  19.  }  
  20.   
  21. function jsonpCallback(result) {     
  22.      if(result.success == true){          
  23.          $('#transport_node').empty();  
  24.          $('#transport_node').append('<option value="0">请选择</option>');  
  25.          $.each(result.transportList, function(i, n){  
  26.              var html = '<option value="'+n.nodeId+'">'+n.transportnodeName+'</option>';  
  27.              $('#transport_node').append(html)   
  28.          });  
  29.       }else{  
  30.          $('#transport_node').empty();  
  31.          $('#transport_node').append('<option value="0">请选择</option>');  
  32.       }   
  33. }    

要点:

1.url中的请求参数callbackFunction=jsonpCallback这是服务器响应返回后调用的javascript方法的名称

2.dataType要为jsonp

 

跨域服务器处理代码:

[java]  view plain copy
 
  1. @RequestMapping("/pagelist/jsonp")  
  2.     public void pagelist(@ModelAttribute TransportNode node,HttpServletRequest httpReq,  
  3.             HttpSession session,HttpServletResponse response) {  
  4.           
  5.         //返回头部设置    
  6.         response.setHeader("Pragma""No-cache");    
  7.         response.setHeader("Cache-Control""no-cache");   
  8.         response.setHeader("Content-type""application/x-javascript;charset=utf-8");  
  9.         response.setDateHeader("Expires"0);    
  10.           
  11.         String jsonpCallback = httpReq.getParameter("callbackFunction");//jsonp回调函数名   
  12.         JSONObject resultJson  = new JSONObject();   
  13.         PrintWriter out = null;        
  14.         try {  
  15.             out = response.getWriter();  
  16.         } catch (IOException e1) {  
  17.             e1.printStackTrace();  
  18.         }    
  19.         try {  
  20.             node.setRowStart((node.getPage() - 1) * node.getRows() + 1);  
  21.             node.setRowEnd(node.getPage() * node.getRows());  
  22.                                       
  23.             resultJson.put("transportList", JsonUtils.toJSONList(business.getList(node)));  
  24.             resultJson.put("success"true);      
  25.             System.out.println(resultJson.toString());  
  26.             out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式数据    
  27.             out.flush();    
  28.             out.close();    
  29.               
  30.         } catch (Exception e) {  
  31.             LogWriter.log("/pagelist/jsonp",e);  
  32.             try {  
  33.                 resultJson.put("success"false);  
  34.             } catch (JSONException e1) {  
  35.                 e1.printStackTrace();  
  36.             }       
  37.             out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式数据    
  38.             out.flush();    
  39.             out.close();    
  40.         }  

注意要点:

1.设置响应报文头,response.setHeader("Content-type", "application/x-javascript;charset=utf-8");,消除了"Resource interpreted as Script but transferred with MIME type text/plain",同时要根据自己的编码格式设置正确的编码;

2.jsonp的数据格式是:jsonpCallback+"("+resultJson.toString()+")"

举个例子:

jsonpCallback({
    "code": "aaa",
    "price": 1780,
    "tickets": 5
});

猜你喜欢

转载自kfq131.iteye.com/blog/2100103
今日推荐