2012-01-07 110 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/