//https://api.douban.com/v2/music/search?q=关键字&callback=回调函数&count=返回条数
;(function(){
var jTpl = document.getElementById('J_searchItemTpl').innerHTML,
oList = document.getElementsByClassName('J_list')[0],
searchInput = document.getElementById('J_searchInput'),
count = 10;
var init = function(){
bindEvent();
}
function bindEvent(){
searchInput.addEventListener('input', debounce(inputChange,500,false), false);
}
function inputChange(){
var value = trimSpace(this.value),
len = value.length;
if(len>0){
getData(value,count);
}else{
showList(false);
}
}
function getData(val,cun){
// var oScript = document.createElement('script');
// oScript.src = 'https://api.douban.com/v2/music/search?q='+val+'&callback='+'setData'+'&count='+count;
// document.body.appendChild(oScript);
// document.body.removeChild(oScript);
xhr.ajax({
url: 'https://api.douban.com/v2/music/search?q='+val+'&count='+count,
type: 'GET',
dataType: 'JSONP',
jsonp:'callback',
success:function(data){
render(data.musics);
}
})
}
// window.setData=function (data){
// console.log(data);
// }
function showList(status){
if(status){
oList.style.display = 'block';
}else{
oList.innerHTML = '';
oList.style.display = 'none';
}
}
function render(data){
var list = '',
dataLen = data.length;
if (dataLen>0) {
data.forEach(function(elem){
list += jTpl.replace(/{{(.*?)}}/g,function(node,key){
return {
url: elem.alt,
image:elem.image,
title:elem.attrs.discs,
singer:elem.attrs.title
}[key]
})
})
oList.innerHTML = list;
showList(true);
};
}
init();
})()
网络-11【JSONP跨域之『豆瓣网音乐搜索』】
最新推荐文章于 2024-06-20 21:48:49 发布