api key를 안받으신분은
2020/02/27 - [ajax 수업] - ajax - API 활용-1 (unsplash.com와 nytimes.com) 가셔서 api key를 발급받으세요!
※ 1. unsplash와 nyt - API 사용하여 이미지 검색하기(jQuery활용)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Make Asynchronous Requests</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<header class="masthead">
<h1>What are you interested in today?</h1>
<div class="site-container">
<form action="#" id="search-form">
<label for="search-keyword" class="visuallyhidden">
what are you interested in today?
</label>
<input type="text" id="search-keyword" placeholder="search" required>
<input id ="submit-btn" type="submit" value="Submit">
</form>
</div>
</header>
<div id="response-container">
<div id="response-container"></div>
</div>
<script src="app.js"></script>
</body>
</html>
style.css
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
background: #fafbfc;
font-family: OpenSans, sans-serif;
margin: 0;
padding: 0;
}
.site-container {
margin: auto;
max-width: 1200px;
width: 80%;
}
.masthead {
background: #2e3d49;
padding: 2em 0;
}
.masthead h1 {
color: #ffffff;
font-weight: normal;
margin: 0;
margin-bottom: 0.2em;
text-align: center;
}
/*** Search Form ***/
#search-form {
display: flex;
padding: 1em 0;
}
#search-keyword {
border: none;
border-radius: 4px;
flex-grow: 1;
margin-right: 1.5em;
padding: 1.25em 2em;
}
#submit-btn {
background-color: #15c26b;
border: none;
border-radius: 4px;
color: #ffffff;
cursor: pointer;
padding: 1em 4em;
text-transform: uppercase;
}
#submit-btn:hover {
background-color: #12a159;
}
/*** Response Container ***/
#response-container {
margin-top: 2em;
}
/*** Image Styline ***/
figure {
margin: 0;
margin-bottom: 2em;
position: relative;
text-align: center;
}
figure img {
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
max-width: 100%;
width: 100%;
}
figcaption {
bottom: 5px;
background: rgba(0, 0, 0, 0.5);
color: #ffffff;
font-size: 14px;
padding: 0.8em 1.4em;
position: absolute;
width: 100%;
}
/*** Helpers ***/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
white-space: nowrap; /* 1 */
}
app.js
(function(){
const form = document.querySelector("#search-form");
const searchField = document.querySelector("#search-keyword");
let searchedForText;
const responseContainer = document.querySelector("#response-container");
const nytAPIKey = "발급받은 apikey";
const unsplashedAPIKey = "발급받은 apikey";
// submt버튼을 눌렀을 때 실행(이벤트를 등록함)
form.addEventListener('submit',function(e){
e.preventDefault();
// ''; << 준이유 초기화한 상태에서 다시 보여주기 위해
responseContainer.innerHTML ='';
// searchField는 입력창
searchedForText = searchField.value;
// UNSPLASHED API, ajax 사용하려면 xmlhttprequest() 사용
const unsplashRequest = new XMLHttpRequest();
$.ajax({
url: `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`,
headers: {
Authorization: `Client-ID ${unsplashedAPIKey}`
}
}).done(addImage)
.fail(function (err) {
requestError(err, 'images');
});
function addImage(data){
let htmlContent='';
// josn 데이터를 javaScipt에서는 텍스트로 인식을 하고 있으므로 javaScript object로 변환해줘야함
// 가장 흔한 예가 Ajax를 사용할 경우이다. Ajax로 호출을 하고 결과값으로 받은responseText로 JSON을 받았을 경우에는
// 그냥 Text이기 때문에 Object로 변환해 주어야 한다.
// data가 존재하고 data.results true가 되고 data.results[0] 배열의 인덱스는 object로 되어있음
if(data && data.results && data.results[0]){
// data.results[0] 에있는 것을 firstImage안에 넣음
const firstImage = data.results[0];
// json 데이터에서 urls.regular를 가져옴
// firstImage에 user.name 것을 가져옴
htmlContent =`<figure>
<img src="${firstImage.urls.regular}" alt="${searchedForText}">
<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
</figure>`;
} else{
htmlContent = '<div class ="error-no-image">No image avaiable<div>';
}
responseContainer.insertAdjacentHTML('afterbegin',htmlContent);
}
//NYT API
const articleRequest = new XMLHttpRequest();
$.ajax({
url: `http://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=${nytAPIKey}`
}).done(addArticles)
.fail(function (err) {
requestError(err, 'images');
});
function addArticles(data) {
let htmlContent = '';
if (data && data.response.docs && data.response.docs[0]) {
htmlContent = '<ul>' + data.response.docs.map(article => `<li class="article">
<h1><a href="${article.web_url}" target="_blank">${article.headline.print_headline}</h1></a>
<h2>${article.headline.main}</h2>
<p>${article.snippet}</p></li>`
).join('') + '</ul>';
} else {
htmlContent = '<div class="error-no-articles">No articles available </div>';
}
responseContainer.insertAdjacentHTML('afterend', htmlContent);
}
});
})();
※ 실행화면
'ajax 수업' 카테고리의 다른 글
ajax - API 활용-1 (unsplash.com와 nytimes.com) (0) | 2020.02.27 |
---|