質問するログイン新規登録

回答編集履歴

1

XMLHttpRequestのコード追記

2016/04/14 14:21

投稿

think49
think49

スコア18194

answer CHANGED
@@ -1,7 +1,69 @@
1
- どこまで理解していてどの辺りで詰まっているのが不明ですが、`XMLHttpRequest` で JSON を入手後、JSON は `JSON.parse` で展開可能です
1
+ どこまで理解していてどの辺りで詰まっているのが不明ですが、`XMLHttpRequest` で JSON を取得してください
2
2
 
3
3
  ```JavaScript
4
4
  'use strict';
5
+ (function () {
6
+ function handleReadystatechange (event) { // XMLHttpRequest Level 1
7
+ var xhr = event.target, object;
8
+
9
+ if (xhr.readyState === 4 && xhr.status === 200) {
10
+ object = JSON.parse(xhr.responseText);
11
+ console.dir(object);
12
+ }
13
+ }
14
+
15
+ function createHandler (_handle, xhr) {
16
+ return handle (event) {
17
+ if (event) {
18
+ event.target = xhr;
19
+ } else {
20
+ event = {target: xhr};
21
+ }
22
+
23
+ _handle.call(xhr, event);
24
+ };
25
+ }
26
+
27
+ function handleLoad (event) { // XMLHttpRequest Level 2
28
+ var xhr = event.target, object;
29
+
30
+ if (xhr.status === 200) {
31
+ object = JSON.parse(xhr.responseText);
32
+ console.dir(object);
33
+ }
34
+ }
35
+
36
+ function main () {
37
+ var xhr = new XMLHttpRequest(); // for IE7+
38
+
39
+ xhr.open('GET', 'data.json', true);
40
+
41
+ if (typeof xhr.addEventListener === 'function') {
42
+ if ('onload' in xhr) {
43
+ xhr.addEventListener('load', handleLoad, false);
44
+ } else if ('onreadystatechange' in xhr) {
45
+ xhr.addEventListener('readystatechange', handleReadystatechange, false);
46
+ }
47
+ } else if (typeof xhr.attachEvent === 'function' || typeof xhr.attachEvent === 'object') { // for IE8-
48
+ if ('onload' in xhr) {
49
+ xhr.attachEvent('onload', createHandler(handleLoad, xhr));
50
+ } else if ('onreadystatechange' in xhr) {
51
+ xhr.attachEvent('onreadystatechange', createHandler(handleReadystatechange, xhr));
52
+ }
53
+
54
+ }
55
+
56
+ xhr.send(null);
57
+ }
58
+
59
+ main();
60
+ }());
61
+ ```
62
+
63
+ JSON は `JSON.parse` で展開可能です。
64
+
65
+ ```JavaScript
66
+ 'use strict';
5
67
  var json = '[{"name":"青木","age":34},{"name":"イチロー","age":41}]',
6
68
  array = JSON.parse(json);
7
69