微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jsonp实现跨域

跨域

什么是跨域?
1.url相同,但端口不同是跨域。
2.ip不同是跨域。

分析
1.js不能跨域请求数据,但是可以跨域请求js片段。
2.把数据包装成js片段,形成一条方法调用语句。
3.浏览器端,先创建回调方法,然后使用ajax请求js片段,在回调函数中通过参数获得后端传过来的数据。

步骤

1.JS

var category = {OBJ: $("#_JD_ALLSORT"),//URL_Serv: "http://manage.taotao.com/web/itemcat/all?callback=category.getDataService",
        //URL_Serv: "http://rest.taotao.com/rest/itemcat/list?callback=category.getDataService",
        URL_Serv: "http://localhost:8081/rest/item/cat/list?callback=category.getDataService",...
  },FN_GetData: function() {
        //使用jsonp来实现跨域请求
        $.getJSONP(this.URL_Serv);
        ...
getDataService: function(a) {
        var b = [],c = this;
        $.each(a.data,function(a) {
            this.index = a,"l" == this.t && (this.i = c.FN_Refactorjson(this.i,7)),b.push(c.renderItem(this,a))
        });
        b.push('<div class="extra"><a {if pageConfig.isHome}clstag="homepage|keycount|home2013|0614a"{/if} href="http://www.jd.com/allSort.aspx">\u5168\u90e8\u5546\u54c1\u5206\u7c7b</a></div>'),this.OBJ.attr("load","1").html(b.join("")),$.bigiframe(this.OBJ),this.FN_GetBrands();
        var d = this,e = this.OBJ.outerWidth(),f = this.OBJ.outerHeight();
        $("#_JD_ALLSORT").dropdown({delay: 0,onmouseleave: function() {
                $("#_JD_ALLSORT .item").removeClass("hover")

2.REST 的controller

@Controller
@RequestMapping("/item/cat")
public class ItemCatController {

    @Autowired
    private ItemCatService itemCatService;

    @RequestMapping(value="/list",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
    @ResponseBody
    public String getItemCatList(String callback){
        ItemCatResult result = itemCatService.getItemCatList();
        //需要把result转换成字符串
        String json = JsonUtils.objectToJson(result);
        if(StringUtils.isBlank(callback)){          
            return json;
        }
        return callback + "(" + json + ");";
    }

}

2.REST 的service

package com.taotao.rest.service;

import com.taotao.rest.pojo.ItemCatResult;

public interface ItemCatService {

ItemCatResult getItemCatList();

}

2.REST 的serviceImpl

package com.taotao.rest.service.impl;

@Service

public class ItemCatServiceImpl implements ItemCatService {

@Autowired 
private TbItemCatMapper itemCatMapper;

@Override
public ItemCatResult getItemCatList() {
    //调用递归方法查询商品分类列表
    List catList = getItemCatList(0l);
    ItemCatResult result = new ItemCatResult();
    result.setData(catList);
    return result;


}

private List getItemCatList(Long parentId){
    //根据parentId查询列表
    TbItemCatExample example = new TbItemCatExample();
    Criteria criteria = example.createCriteria();
    criteria.andParentIdEqualTo(parentId);

    List<TbItemCat> list = itemCatMapper.selectByExample(example);
    List resultList = new ArrayList<>();
    int index = 0;
    for(TbItemCat tbItemCat : list){
        if(index >= 14){
            break;
        }
        //如果是父节点
        if (tbItemCat.getIsParent()){
            CatNode node = new CatNode();
            node.setUrl("/products/"+tbItemCat.getId()+".html");
            //如果当前节点是第一级节点
            if(tbItemCat.getParentId()==0){                 
                node.setName("<a href='/products/"+tbItemCat.getId()+".html'>"+tbItemCat.getName()+"</a>");
                index++;
            }else{
                node.setName(tbItemCat.getName());

            }
            node.setItems(getItemCatList(tbItemCat.getId()));
            //把node添加到列表
            resultList.add(node);
        }else{
            //如果是叶子节点
            String item = "/products/"+tbItemCat.getId()+".html|" + tbItemCat.getName();
            resultList.add(item);
        }           
    }
    return resultList;
}

}

3.pojo–itemCatResult

package com.taotao.rest.pojo;

import java.util.List;

public class ItemCatResult {
private List data;

public List getData() {
    return data;
}

public void setData(List data) {
    this.data = data;
}

}

4.pojo–catNode

package com.taotao.rest.pojo;

public class CatNode {
@JsonProperty(“u”)
private String url;
@JsonProperty(“n”)
private String name;
@JsonProperty(“i”)
private List items;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}

}

5.调用流程

小结

跨域调用的一种方法jsonp,梳理完一条线就更清晰了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐