2012-01-07 112 views
2

我需要從遠程URL動態加載JavaScript文件,但在將它附加到標頭之前,我必須對收到的腳本進行一些更改。jquery ajax在GET中刪除換行符

的問題是:我得到的JS文件的內容,而不換行符,所以如果有一些評論裏 - 所有的腳本停止工作..

我使用的代碼是:

 $.ajax({ 
      url: filename, 
      type: "GET", 
      success: function (res) { 
       var ver = $(res.responseText); 
       var jsContent = $(ver).text(); 

       jsContent = jsContent.replace('..', '...'); 

       var oScript = document.createElement("script"); 
       oScript.language = "javascript"; 
       oScript.type = "text/javascript"; 
       oScript.defer = true; 
       oScript.text = jsContent; 
       document.getElementsByTagName("head")[0].appendChild(oScript); 
      } 
     }); 

任何想法?

+0

有沒有原因你不能修改正在加載的腳本?我不認爲有一種方法做你想要什麼,而不必使用eval – 2012-01-07 16:13:02

+0

你試過使用'$ .get()'而不是'$ .ajax()'嗎?理論上他們是相同的,但[有一些後者帶狀線斷裂](http://stackoverflow.com/questions/7017068/why-does-jquery-ajax-remove-line-breaks-in-data-and-get -doesnt)。 – 2012-01-07 16:15:16

回答

5

,如果你只是想動態加載js文件,那麼你需要設置數據類型爲「腳本」或使用.getScript功能

$.ajax({ 
     url: filename, 
     type: "GET", 
     dataType:"script", 
     success: function (res) { 

     } 
    }); 

$.getScript(url); 

http://api.jquery.com/jQuery.getScript/