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

回答編集履歴

1

修正とES6構文の追記

2018/07/03 02:28

投稿

og24715
og24715

スコア832

answer CHANGED
@@ -1,31 +1,6 @@
1
- おそらく以下のコードの `onload` の中と外でスコープが異なるからではないですかね。
1
+ ~~おそらく以下のコードの `onload` の中と外でスコープが異なるからではないですかね。~~
2
+ 変数`obj`外で定義してましたね。 maisumakun さんのとおり `$.getJSON`が非同期なのが原因ですね。
2
3
 
3
- ```js
4
- script.onload = function() {
5
- var $ = window.jQuery;
6
- obj = $.getJSON('https://yuis.xsrv.jp/cdn/dev.json', function(data) {});
7
- };
8
- document.getElementsByTagName("head")[0].appendChild(script);
9
-
10
- json = obj.responseJSON; // responseJSON is undefined!
11
- console.log(json.keywords) ;
12
- ```
13
-
14
- 以下のように同じスコープで実行すると正しく動作するかと思います。
15
-
16
- ```js
17
- script.onload = function() {
18
- var $ = window.jQuery;
19
- obj = $.getJSON('https://yuis.xsrv.jp/cdn/dev.json', function(data) {});
20
- json = obj.responseJSON;
21
- console.log(json.keywords) ;
22
- };
23
-
24
- ```
25
-
26
- ---
27
-
28
-
29
4
  質問の回答とは逸れてしまいますが、 ajax が目的でしたら特に理由がない限りブラウザ標準の fetchAPI を使ったほうが簡単でいいと思います。(IE未実装)
30
5
 
31
6
  ```js
@@ -48,9 +23,24 @@
48
23
  .then(json => { // 引数が一つなら () を省略できる
49
24
  console.log(json);
50
25
  });
26
+ ```
51
27
 
28
+ さらに async/await を使うと
29
+
30
+ ```js
31
+ const getJson = async url => {
32
+ const response = await fetch(url);
33
+ const json = await response.json();
34
+ return json;
35
+ };
36
+
37
+ const url = 'https://yuis.xsrv.jp/cdn/dev.json';
38
+ const json = getJson(url);
39
+ console.log(json);
52
40
  ```
53
41
 
42
+ と出来ます。
43
+
54
44
  ### 参考
55
45
  [When (and why) you should use ES6 arrow functions — and when you shouldn’t](https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26)
56
46
  [お疲れさまXMLHttpRequest、こんにちはfetch - Qiita](https://qiita.com/tomoyukilabs/items/9b464c53450acc0b9574)