Javascript 如何正确地从iTunesAPI获取数据?
因此,我尝试使用vanilla JavaScript,从iTunes的API中提取数据,创建一个页面,允许用户输入艺术家的名字,然后编译一个包含15个顶级结果的页面。我正在使用以下内容进行获取:Javascript 如何正确地从iTunesAPI获取数据?,javascript,fetch-api,Javascript,Fetch Api,因此,我尝试使用vanilla JavaScript,从iTunes的API中提取数据,创建一个页面,允许用户输入艺术家的名字,然后编译一个包含15个顶级结果的页面。我正在使用以下内容进行获取: function dataPull() { fetch("https://itunes.apple.com/search?term=") .then(function(response) { if (response.status !== 200) { consol
function dataPull() {
fetch("https://itunes.apple.com/search?term=")
.then(function(response) {
if (response.status !== 200) {
console.log(response.status);
return;
}
response.json().then(function(data){
console.log(data);
let returnResponse = document.createElement("div");
let input2 = inputElement.value;
for (let i=0; i<data.length; i++){
if (inputElement===data[i].artistName){
console.log(data[i].artistName);
returnResponse.innerHTML = `
<div class="box">
<img src=${artWorkUrl30} alt="Album Image">
<p><span>Artist Name:</span>${data[i].artistName}</p>
<p><span>Track: </span>${data[i].trackName}</p>
<p><span>Album Name: </span>${data[i].collectionName}</p>
<p><span>Album Price: </span>${data[i].collectionPrice</p>
</div>
`;
results.appendChild(returnResponse);
}}
console.log(data);
});
}
)
函数dataPull(){
取回(“https://itunes.apple.com/search?term=")
.然后(功能(响应){
如果(response.status!==200){
console.log(响应状态);
返回;
}
response.json().then(函数(数据){
控制台日志(数据);
让returnResponse=document.createElement(“div”);
让input2=inputElement.value;
for(设i=0;i典型的fetch
调用如下所示
fetch(`${url}`)
.then(response => response.json())
.then(json =>
// do something with the json
)
修改代码,看看是否可以console.log()
任何值得注意的内容。典型的fetch
调用如下所示
fetch(`${url}`)
.then(response => response.json())
.then(json =>
// do something with the json
)
修改您的代码,看看您是否可以console.log()
任何值得注意的内容。我建议您分离您的关注点。使dataPull函数只获得结果。这意味着您可以在其他地方使用此代码,而无需更改它
在这里,函数返回json对象作为承诺
function dataPull(search) {
return fetch("https://itunes.apple.com/search?term="+search).then(res => res.json());
}
不,您可以调用dataPull函数并解决承诺。您将得到结果,并可以使用它做您想做的事情
dataPull("test").then(res => {
console.log(res.results);
/*
res.results.forEach(item => {
div and span magic here
})
*/
})
这里有一个指向正在工作的JSFIDLE的链接。
我建议将您的关注点分开。使dataPull函数只得到结果。这意味着您可以在其他地方使用此代码,而无需更改它
在这里,函数返回json对象作为承诺
function dataPull(search) {
return fetch("https://itunes.apple.com/search?term="+search).then(res => res.json());
}
不,您可以调用dataPull函数并解决承诺。您将得到结果,并可以使用它做您想做的事情
dataPull("test").then(res => {
console.log(res.results);
/*
res.results.forEach(item => {
div and span magic here
})
*/
})
这里有一个指向正在工作的JSFIDLE的链接。
当响应状态不是200时,不获取JSON正文没有问题。当响应状态不是200时,不获取JSON正文没有问题。您查看了吗?您查看了吗?