Javascript 搜索为空字符串或与API调用不匹配
如果搜索是空字符串,或者在输入字段的值上找不到api中的任何匹配项,如何捕获并打印消息给用户Javascript 搜索为空字符串或与API调用不匹配,javascript,api,Javascript,Api,如果搜索是空字符串,或者在输入字段的值上找不到api中的任何匹配项,如何捕获并打印消息给用户 // show the search results from user input const searchTvShows = ({ target }) => { fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`) .then(blob => blob.json()) .the
// show the search results from user input
const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ');
})
}
我刚刚检查过,当成功搜索不匹配项时,API返回一个空数组,因此:
if (shows.length) {
// do what you're doing
} else {
// show a message saying there were no matches
}
在此背景下,同时处理我在以下章节中提到的问题:
这是因为对于空数组,.join“”将返回falsy,因此| |。。。结果。。。。但是,如果数组不是空的,您将有一个非空字符串,这将是真实的。当没有结果时,api会返回什么?旁注:与许多人一样,您在上面遗漏了两个非常重要的内容:1。您需要检查响应的ok属性,fetch不会拒绝,除非网络出现故障,例如404s仍然解析。2.您需要处理错误,例如.catcherr=>{/*handle it*/}。fetch使用类app获取div,这样我们就可以在app中追加另一个div。但是我不知道我们是否能用同样的方法。。。。当没有结果时,它只在结果应该显示的地方返回空白be@Lacon,请取消删除代码审阅线程简化Javascript代码。我已经复习了一个半小时了。如果你能把它放回网上,我就可以给你我的答案了。非常感谢。
const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(response => {
if (!response.ok) {
throw new Error();
}
return response;
})
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
if (shows.length) {
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ');
} else {
app.innerHTML = "<em>No matching shows</em>";
}
})
.catch(err => {
// Report the error or similar
})
}
const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(response => {
if (!response.ok) {
throw new Error();
}
return response;
})
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ') || "<em>No matching shows</em>"; // ***
})
.catch(err => {
// Report the error or similar
})
}