【跨域】jsonp跨域实现方法
封装原生jsonp:
以跨域调取豆瓣电影最热榜单为例:
function $jsonp(url,data,callback){ var funcName = 'jsonp_cb' + Math.random().toString().replace('.',''); window[funcName] = callback; var querystring = url.indexOf('?') === -1? '?':'&'; for(key in data) { querystring += key + '=' + data[key] + '&' } url += querystring + 'callback=' + funcName; // 此处的‘callback’根据API接口要求更改 console.log(url); var newScript = document.createElement('script') newScript.src = url; document.body.appendChild(newScript); } $jsonp('http://api.douban.com/v2/movie/in_theaters',{count:10,start:5},function(data){ console.log(JSON.stringify(data)); });
jQuery实现:
$.ajax({ url:'http://api.douban.com/v2/movie/in_theaters', type:'get', data:{count:10,start:5}, dataType:'jsonp', success:function(data){ ... } })