Created
April 11, 2020 16:22
-
-
Save pistachiyoda/ca9b61d380b3c1dcb1772dbe3b1a2a54 to your computer and use it in GitHub Desktop.
js-primer(ajax)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html lang="ja"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Ajax Example</title> | |
</head> | |
<body> | |
<h2>GitHub User Info</h2> | |
<input id="userId" type="text" value="js-primer-example" /> | |
<button onclick="main();">Get user info</button> | |
<div id="result"></div> | |
<script src="index.js"></script> | |
</body> | |
</html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function main() { | |
try { | |
const userId = getUserId(); | |
const userInfo = await fetchUserInfo(userId); | |
const view = createView(userInfo); | |
displayView(view); | |
} catch (error) { | |
console.error(`エラーが発生しました(${error})`); | |
} | |
} | |
function fetchUserInfo(userId) { | |
return fetch( | |
`https://api.github.com/users/${encodeURIComponent(userId)}` | |
).then((response) => { | |
console.log(response.status); | |
if (!response.ok) { | |
return Promise.reject( | |
new Error(`${response.status}: ${response.statusText}`) | |
); | |
} else { | |
return response.json(); | |
} | |
}); | |
} | |
function getUserId() { | |
const value = document.getElementById("userId").value; | |
return encodeURIComponent(value); | |
} | |
function createView(userInfo) { | |
return escapeHTML` | |
<h4>${userInfo.name} (@${userInfo.login})</h4> | |
<img src="${userInfo.avatar_url}" alt="${userInfo.login}" height="100"> | |
<dl> | |
<dt>Location</dt> | |
<dd>${userInfo.location}</dd> | |
<dt>Repositories</dt> | |
<dd>${userInfo.public_repos}</dd> | |
</dl> | |
`; | |
} | |
function displayView(view) { | |
const result = document.getElementById("result"); | |
result.innerHTML = view; | |
} | |
function escapeSpecialChars(str) { | |
return str | |
.replace(/&/g, "&") | |
.replace(/</g, "<") | |
.replace(/>/g, ">") | |
.replace(/"/g, """) | |
.replace(/'/g, "'"); | |
} | |
function escapeHTML(strings, ...values) { | |
return strings.reduce((result, str, i) => { | |
const value = values[i - 1]; | |
if (typeof value === "string") { | |
return result + escapeSpecialChars(value) + str; | |
} else { | |
return result + String(value) + str; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment