Skip to content

Instantly share code, notes, and snippets.

@pistachiyoda
Created April 11, 2020 16:22
Show Gist options
  • Save pistachiyoda/ca9b61d380b3c1dcb1772dbe3b1a2a54 to your computer and use it in GitHub Desktop.
Save pistachiyoda/ca9b61d380b3c1dcb1772dbe3b1a2a54 to your computer and use it in GitHub Desktop.
js-primer(ajax)
<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
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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
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