$.getJSON()を使ってファイルを読み込み、読み込んだデータを処理するプログラムを作りたいのですが、読み込み完了する前に、データを加工する処理が走ってしまい思ったような処理結果になりません。
ブラウザで開発者ツールのconsoleを見ると、$getJSON()の成功時コールバックに指定した関数は最初に処理完了することを期待していたのですが、非同期に呼び出されたのか?最後に処理されているように見えます。
もし非同期に処理されるのならば、$.getJSON()呼び出しが終わるまで待つ(完了復帰)か、読み終わったことを知るコールバックを指定することはできないでしょうか?
以下、実験プログラムと実行結果です。
main.js:
javascript
1(function ($) { 2 'use strict'; 3 4 var program = new Program(1); // ファイルのラッパクラス 5 program.loadJSON(); // この中で呼び出す$.getJSON()が完了復帰でない? 6 7 // DOMが全て読み込まれてから処理を開始する 8 $(function () { 9 program.printData(); // 読み込んだJSONを表示する 10 program.deleteFirst(); // JSON中最初のオブジェクトを削除する 11 program.printData(); // 削除後のJSONを表示する 12 13 console.log('DOM ready'); 14 }); 15 16 17 console.log($('title').text() + ' initialized'); 18 19}(jQuery)); 20
Program.js:
javascript
1var Program = (function () { 2 3 function Program(no) { 4 this.no = no; 5 this.data = []; 6 } 7 8 Program.prototype.loadJSON = function () { 9 var filename = "program" + this.getNo() + ".json"; 10 $.getJSON(filename, function(data) { 11 this.data = data; 12 console.log("data= " + JSON.stringify(this.data)); // なぜこのログが最後に出るのか? 13 }); 14 } 15 16 Program.prototype.deleteFirst = function () { 17 this.data.splice(0, 1); 18 console.log("new length= " + this.data.length); 19 } 20 21 Program.prototype.printData = function () { 22 console.log(this.data); 23 } 24 25 Program.prototype.getNo = function () { 26 return this.no; 27 } 28 29 return Program; 30})();
main.html:
html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>example of count down</title> 6 <link rel="stylesheet" type="text/css" href="css/main.css"> 7 <script src="js/jquery-1.8.3.js" type="text/javascript"></script> 8</head> 9<body> 10<script type="application/javascript" src="js/Program.js"></script> 11<script type="application/javascript" src="js/main.js"></script> 12</body> 13</html>
program1.json:
json
1[ 2 { 3 "time": "00:00:00", 4 "duration": 5, 5 "title": "タイトル1" 6 }, 7 { 8 "time": "00:00:05", 9 "duration": 5, 10 "title": "タイトル2本目" 11 }, 12 { 13 "time": "00:00:10", 14 "duration": 5, 15 "title": "最後のタイトル" 16 } 17]
処理結果: data=で始まる箇所は最初に処理を終えておいて欲しい
text
1example of count down initialized main.js:16 2[] 3new length= 0 4[] 5DOM ready 6data= [{"time":"00:00:00","duration":5,"title":"タイトル1"},{"time":"00:00:05","duration":5,"title":"タイトル2本目"},{"time":"00:00:10","duration":5,"title":"最後のタイトル"}]

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/08/13 22:44 編集