ajax跨域請求--jsonp執行個體

來源:互聯網
上載者:User

標籤:ajax   jsonp   


ajax請求代碼:

//地區事件選擇配送點function changeDistrict(value){ if(value == 0){     $('#transport_node').empty();     $('#transport_node').append('<option value="0">請選擇</option>');     return; } $('#transport_node').empty(); $('#transport_node').append('<option value="0">載入中...</option>'); $.ajax({         type: 'GET',         url: "http://192.168.33.114:8080/UIDTraceAdmin/transportnode/pagelist/jsonp?callbackFunction=jsonpCallback",         async: false,         dataType: "jsonp",         jsonp: "jsonpCallback",//傳遞給請求處理常式或頁面的,用以獲得jsonp回呼函數名的參數名(一般預設為:callback)         success: function(o){},         timeout:3000       }); }function jsonpCallback(result) {    if(result.success == true){     $('#transport_node').empty();     $('#transport_node').append('<option value="0">請選擇</option>');         $.each(result.transportList, function(i, n){        var html = '<option value="'+n.nodeId+'">'+n.transportnodeName+'</option>';             $('#transport_node').append(html)          });      }else{        $('#transport_node').empty();        $('#transport_node').append('<option value="0">請選擇</option>');      } }  

要點:

1.url中的請求參數callbackFunction=jsonpCallback這是伺服器響應返回後調用的javascript方法的名稱

2.dataType要為jsonp


跨網域服務器處理代碼:

@RequestMapping("/pagelist/jsonp")public void pagelist(@ModelAttribute TransportNode node,HttpServletRequest httpReq,HttpSession session,HttpServletResponse response) {//返回頭部設定          response.setHeader("Pragma", "No-cache");          response.setHeader("Cache-Control", "no-cache");         response.setHeader("Content-type", "application/x-javascript;charset=utf-8");        response.setDateHeader("Expires", 0);                  String jsonpCallback = httpReq.getParameter("callbackFunction");//jsonp回呼函數名         JSONObject resultJson  = new JSONObject();         PrintWriter out = null;      try {out = response.getWriter();} catch (IOException e1) {e1.printStackTrace();}  try {node.setRowStart((node.getPage() - 1) * node.getRows() + 1);node.setRowEnd(node.getPage() * node.getRows());      resultJson.put("transportList", JsonUtils.toJSONList(business.getList(node)));resultJson.put("success", true);        System.out.println(resultJson.toString());        out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式資料          out.flush();          out.close();          } catch (Exception e) {LogWriter.log("/pagelist/jsonp",e);try {resultJson.put("success", false);} catch (JSONException e1) {e1.printStackTrace();}         out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式資料          out.flush();          out.close();  }

注意要點:

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
});





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.