jquery Ajax 跨域調用(jsonp)

來源:互聯網
上載者:User

最近一直在做電子商務方面的項目,包括買家和賣家後台 分別在seller.com 和buyer.com 還有前台www.xxx.com
其中有一個查看商品二級分類的下拉框 需要查詢 當時沒有考慮到這三個項目都會用到 就放到了前台的代碼中,後台需求的變化,賣家和買家後台也要用到這個介面
由於初始化前台頁面的時候是用ajax的方式初始化這個下拉框的,所以其他的平台的調用也想到了這個問題,緊接著就遇到ajax跨域的問題 ,下面來提供解決的方法。

下面是action的代碼 由三個系統共同調用

public class HeadAction extends BaseAction{private HttpServletRequest request;private HttpServletResponse response;public void findSecondCat(){ActionContext ctx = ActionContext.getContext();    request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);    response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);     //response.setHeader("Cache-Control", "no-cache");    response.setContentType("text/json;charset=utf-8");String catType = request.getParameter("catType");List<CategoryNode> node = CategoryCache.getAllCategoryNodes(1, Integer.parseInt(catType));//調用緩衝查詢分類try {PrintWriter  out = response.getWriter();JSONArray ja = new JSONArray();for(CategoryNode c: node){//返回json格式JSONObject j = new JSONObject();j.put("id", c.ID);j.put("name", c.Name);ja.add(j);}  String cb = request.getParameter("callback");//若果是ajax請求會帶這個參數 你可以firfox的firbug跟蹤一下就看到了    if(cb != null){//如果是跨域  StringBuffer sb = new StringBuffer(cb);  sb.append("(");  sb.append(ja.toString());  sb.append(")");  out.write(sb.toString());out.close();  }else{//不跨域的情況  out.write(ja.toString());out.close();  }} catch (IOException e) {e.printStackTrace();}}}

下面是js代碼

$.ajax( { type : 'get',url : '<%=com.utils.PubConstant.wwwDomain %>/index/findSecondCat.action',data : {catType : 1},dataType : 'jsonp',//跨域必須用jsonperror : function() {},success : function(data) {innerOption = "<option value=''>全部分類</option>";for(var i=0;i<data.length;i++){                             innerOption += '<option value="'+data[i].id+'">'+data[i].name+'</option>';                             };$('#secondCatIdId').html(innerOption);$("#lang, #secondCatIdId").jListbox();}});

這樣就可以跨域進行ajax請求了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.