通过Promise和JQuery获取网易云音乐热评

方法一:

function createPromise(url){
//在Promise对象中封装好ajax请求然后返回出去
	return new Promise(function(resolve,reject){
		$.ajax({
			url,
			type:'get',
			dataType:'json',
			success(arr){
				resolve(arr);
			},
			error(err){
				reject(err);
			}
		});
	});
}
Promise.all([//分别执行发送请求
	createPromise('https://api.imjad.cn/cloudmusic/?type=comments&id=478963730'),
	createPromise('https://api.imjad.cn/cloudmusic/?type=comments&id=28012031')
]).then(data=>{//两个请求都成功后执行,用循环将数据渲染到页面
	console.log(data);
	var [hotComments1,hotComments2]=["",""];
	for(var i=0;i<10;i++){//只输出10条热评
		hotComments1+=`<p>
			用户昵称:<b>${data[0].hotComments[i].user.nickname}</b>,
			用户评论:<b>${data[0].hotComments[i].content}</b>
		</p>`;
		hotComments2+=`<p>
			用户昵称:<b>${data[1].hotComments[i].user.nickname}</b>,
			用户评论:<b>${data[1].hotComments[i].content}</b>
		</p>`;					
	}//将2份数据写到页面中
	$("#div1").html(hotComments1+hotComments2);				
},error=>console.log(`请求失败`));

运行结果:
在这里插入图片描述

方法二(改进):

jquery自身支持Promise

/*引入的jqeury版本不能太低,这里用的是3.4.1版*/
Promise.all([
	$.ajax({url:'https://api.imjad.cn/cloudmusic/?type=comments&id=478963730',dataType:'json'}),
	$.ajax({url:'https://api.imjad.cn/cloudmusic/?type=comments&id=28012031',dataType:'json'})
]).then(results=>{//两个请求都成功后执行,分别调用函数将数据渲染到页面
	let [arr,json]=results;
	console.log(results);
	console.log(`成功了`);
	hotcomments(arr);
	hotcomments(json);
},error=>console.log(`失败了`));
		
function hotcomments(data){
	for(var i=0;i<10;i++){//只输出10条热评
		div1.innerHTML+=`<p>
			用户昵称:<b>${data.hotComments[i].user.nickname}</b>,
			用户评论:<b>${data.hotComments[i].content}</b>
		</p>`;
	}
}

运行结果:
在这里插入图片描述
成功拿到😄😄😄

使用的API参考自:网易云音乐API

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值