我在服务器中有一个javascript文件,我无法修改。
以下是我必须下载的脚本示例:
var tags = '';
tags += '<a href="#somelink"><img src="someimage.gif"/></a>;
document.write(tags);
我开始通过AJAX下载脚本并执行它,但我碰到了“document.write无法在异步调用中执行”的问题。
因此,我希望将该脚本作为纯文本下载并从响应中获取我需要的内容,并将其放在我应该放在html页面中的位置,而不需要修改原始脚本。
$.ajax({
type: "GET",
url: "http://myurlexample.com",
dataType: "text",
}).success(function(msg){
console && console.log("The script was downloaded as text: "+msg);
}).error(function(object,status,errortxt){
console && console.log("The script wasn't downloaded as text. The error:"+ errortxt);
});
但是当我使用dataType = "text"
执行下载请求时,AJAX会抛出错误。有什么方法可以解决这个问题并将其作为文本下载吗?
P.S:该脚本适用于Firefox OS特权应用,因此我无法将脚本直接放在html页面中,因为安全CSP不允许它(https://developer.mozilla.org/en-US/Apps/CSP)。
答案 0 :(得分:1)
由于您似乎能够以某种方式成功运行脚本,因此这可能有用:包覆document.write
。
在运行脚本之前,请执行以下操作:
document.write = function(msg) {
handleTagStringInApp(msg);
delete document.write; // revert to original document.write when done
};
// now load execute the script...
其中handleTagStringInApp
是您编写的函数,以某种方式处理标记字符串。这基本上是JSONP,但您无法将回调名称调整为不显眼或有用的内容,而必须使用回调名称document.write
。
请注意,如果您的应用中的其他内容确实需要使用document.write
,则非常糟糕。 (您可以通过保留对真实document.write
的引用来解决此问题,例如,在页面加载时使用var realDocWrite = document.write;
并使用realDocWrite.call(document, "whatever")
调用它。)