百度API调用时会出现跨域,导致been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
使用JSONP的解决方案如下:
封装IP函数
function getIp(ip) { var url = 'http://api.map.baidu.com/location/ip?ak=11Z8uiP8kIz6AG0Vjiwzbc5f9Ii0cdHd&ip=' + ip + '&coor=bd09ll&callback=callBack'; return url; }
生成script
//生成script function createScript(src) { var el = document.createElement('script'); console.log(el); el.src = src; document.body.appendChild(el); }
回调函数
//回调函数 function callBack(rs) { var city = rs['content']['address']; console.log(city); }
执行渲染
createScript(getIp("39.185.200.145"));
Done!