htmlファイルに<script src="">
で読み込むファイルを1つに抑えたい為、読み込むjsファイルに下記のようなコードを書きました。
XMLHttpRequestを使って別のjsファイルを読み込んでいます。
js
1var xhr = null; 2if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); 3else if(window.ActiveXObject){ 4 5 try{ 6 7 xhr = new ActiveXObject("Msxml2.XMLHTTP"); 8 } catch(e){ 9 10 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 11 } 12} 13xhr.open("GET", "https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js", false); 14xhr.send(""); 15eval(xhr.responseText); 16 17function getSyohinData(syohincode, resultfunction) { 18 "use strict"; 19 20 $(function () { 21 22 $.post({ 23 24 url: "Syohin.aspx", 25 data: "syohincode=" + syohincode, 26 dataType: 'json' 27 }).done(function (data) { 28 29 resultfunction(data); 30 }); 31 }); 32}
現在はこれで動いているのですが、コンソール画面に、XMLHttpRequestは廃止予定だと警告が出て来るので、別の方法を取りたいです。
調べてみると、XMLHttpRequestの代わりにfetchを使えというサイトがあったので試してみましたが、非同期処理のため、多分ajaxのjsが読み込まれる前に下のgetSyohinData()が読み込まれてしまい、エラーになりました。
fetchを同期処理に出来ないかと思い、async: false
を追加してみましたがまだエラーになります。
現在のコード
js
1fetch( 2 "https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js", 3 { 4 method: "GET", 5 async: false 6 } 7).then( 8 response => response.text() 9).then( 10 text => { 11 eval(text); 12 } 13); 14 15function getSyohinData(syohincode, resultfunction) { 16 "use strict"; 17 18 $(function () { 19 20 $.post({ 21 22 url: "Syohin.aspx", 23 data: "syohincode=" + syohincode, 24 dataType: 'json' 25 }).done(function (data) { 26 27 resultfunction(data); 28 }); 29 }); 30}
エラーUncaught ReferenceError: $ is not defined
同期/非同期とかとは別の原因でしょうか?
他にやり方はありませんでしょうか?
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。