Skip to content

Commit f465cf9

Browse files
committed
[jsprimer] add
1 parent 934673c commit f465cf9

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

jsprimer/index.html

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<html lang="ja">
2+
<head>
3+
<meta charset="utf-8" />
4+
<title>Ajax Example</title>
5+
</head>
6+
<body>
7+
<h1>GitHub User Info</h1>
8+
9+
<input id="userId" text="text" value="js-primer-example" />
10+
<button onclick="main();">Get user info</button>
11+
12+
<div id="result"></div>
13+
14+
<script src="index.js"></script>
15+
</body>
16+
</html>

jsprimer/index.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
console.log("index.js: loaded");
2+
3+
function escapeSpecialChars(str) {
4+
return str
5+
.replace(/&/g, "&amp;")
6+
.replace(/</g, "&lt;")
7+
.replace(/>/g, "&gt;")
8+
.replace(/"/g, "&quot;")
9+
.replace(/'/g, "&#039;");
10+
}
11+
12+
function escapeHTML(strings, ...values) {
13+
return strings.reduce((result, str, i) => {
14+
const value = values[i - 1];
15+
if (typeof value === "string") {
16+
return result + escapeSpecialChars(value) + str;
17+
} else {
18+
return result + String(value) + str;
19+
}
20+
})
21+
}
22+
23+
function createView(userInfo) {
24+
return escapeHTML`
25+
<h4>${userInfo.name} (@${userInfo.login})</h4>
26+
<img src="${userInfo.avatar_url}" alt="${userInfo.login}" height="100">
27+
<dl>
28+
<dt>Location</dt>
29+
<dd>${userInfo.location}</dd>
30+
31+
<dt>Repositories</dt>
32+
<dd>${userInfo.public_repos}</dd>
33+
</dl>
34+
`;
35+
}
36+
37+
function displayView(view) {
38+
const result = document.getElementById("result");
39+
result.innerHTML = view;
40+
}
41+
42+
function fetchUserInfo(userId) {
43+
return fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`)
44+
.then(response => {
45+
if (!response.ok) {
46+
return Promise.reject(new Error(`${response.status}: ${response.statusText}`));
47+
} else {
48+
return response.json();
49+
}
50+
});
51+
}
52+
53+
function getUserId() {
54+
const value = document.getElementById("userId").value;
55+
return encodeURIComponent(value);
56+
}
57+
58+
async function main() {
59+
try {
60+
const userId = getUserId();
61+
const userInfo = await fetchUserInfo(userId);
62+
const view = createView(userInfo);
63+
displayView(view);
64+
} catch (error) {
65+
console.error(`エラーが発生しました (${error})`);
66+
}
67+
}

0 commit comments

Comments
 (0)