jsonp('http://photo.sina.cn/aj/index', {
page: 1,
cate: 'recommend'
}, 'jsoncallback').then(res => {
console.log(res.data);
}).catch(err=>{
console.log(err);
})
function jsonp(url,data,callback){
return new Promise((resolve)=>{
var script = document.createElement('script')
url += `?jsoncallback=${callback}`
if(data){
Object.keys(data).forEach(key=>{
url += `&${key}=${data[key]}`
})
}
script.src = url
document.head.appendChild(script)
window[callback] = function (data){
resolve(data)
}
script.parentNode.removeChild(script)
})
}
jsonp('http://photo.sina.cn/aj/index', {
page: 1,
cate: 'recommend',
}, 'jsoncallback').then(res => {
console.log(res.data);
}).catch(err=>{
console.log(err);
})
function jsonp(url,data,callbackName){
data.callback = callbackName?callbackName : 'callback';
let paramArr = []
for(let key in data){
paramArr.push(`${key}=${data[key]}`);
}
let script = document.createElement('script')
let body = document.getElementsByTagName('body')[0]
script.src = url + '?' + paramArr.join('&')
body.appendChild(script)
return new Promise((resolve,rejiect)=>{
window[callbackName] = (data)=>{
resolve(data)
document.body.removeChild(script)
}
})
}