jQuery Ajax 跨域调用
由于初始化前台页面的时候是用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();
- }
- }
- }
- $.ajax( {
- type : 'get',
- url : '<%=com.utils.PubConstant.wwwDomain %>/index/findSecondCat.action',
- data : {
- catType : 1
- },
- dataType : 'jsonp',//跨域必须用jsonp
- error : 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();
- }
- });
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20