2015-01-09 79 views
0

我正在將data.js加載到我的a.html頁面中。動態加載後無法使用jquery

在我的data.js,我檢查如果a.html有jquery並加載它,如果不是。加載jquery後,我正在做一個阿賈克斯電話,但我越來越

$ is not defined 

異常。

這裏是我的data.js

if(typeof jQuery=='undefined') { 
      var headTag = document.getElementsByTagName("head")[0]; 
      var jqTag = document.createElement('script'); 
      jqTag.type = 'text/javascript'; 
      jqTag.src = 'http://localhost:8001/jquery-min.js'; 
      headTag.appendChild(jqTag); 
     } 

     var url = 'http://127.0.0.1:5000'; 

     $.ajax({ 
      url: url, 
      success: function(data) { 
       $("#" + containerId).html(data); 
      }, 
      error: function(e) { 

       console.log(e.message); 
      } 
     }); 

從開發者控制檯,我可以看到jQuery是加載。我可以在資源和標籤中看到它。

+1

而在你的開發者控制檯,你得到任何錯誤? – adeneo 2015-01-09 19:37:23

+1

您的ajax調用在加載jQuery文件之前正在運行。 – isherwood 2015-01-09 19:37:30

+0

@adeneo我得到$是未定義的錯誤,它已經存在問題。 – 2015-01-09 19:38:04

回答

2

由於您只是將腳本標記添加到您的DOM,所以當您進行AJAX調用時,尚未加載jQuery(和$)。之後它開始下載。相反,您應該綁定腳本標記的onload事件並在加載後執行操作。

jqTag.onload = function() { 
    var url = 'http://127.0.0.1:5000'; 

    $.ajax({ 
     url: url, 
     success: function(data) { 
      $("#" + containerId).html(data); 
     }, 
     error: function(e) { 

      console.log(e.message); 
     } 
    }); 
} 
jqTag.src = 'http://localhost:8001/jquery-min.js'; 
+0

我怎麼理解它的加載? – 2015-01-09 19:39:18

-3

改變這一行:

if(typeof jQuery=='undefined')

if(typeof jQuery== undefined) { 
+2

'typeof'總是返回一個字符串,這樣做的條件永遠不會是真的? – adeneo 2015-01-09 19:46:04