这是我正在尝试完成的: 获取“外部”网址的静态内容并检查特定关键字,例如“用户指南”或“未找到网页”。如何在JavaScript变量中存储网页的静态内容?
我试图使用Ajax,dojo.xhr等,但他们不支持跨域。在我的情况下,它是一个外部网址。另外,我不能使用jQuery。
我也看过dojo.io.iframe,但我找不到有用的例子来完成这个。
dojo.io.iframe示例会非常有帮助。 请帮忙。
谢谢!
这是我正在尝试完成的: 获取“外部”网址的静态内容并检查特定关键字,例如“用户指南”或“未找到网页”。如何在JavaScript变量中存储网页的静态内容?
我试图使用Ajax,dojo.xhr等,但他们不支持跨域。在我的情况下,它是一个外部网址。另外,我不能使用jQuery。
我也看过dojo.io.iframe,但我找不到有用的例子来完成这个。
dojo.io.iframe示例会非常有帮助。 请帮忙。
谢谢!
现代浏览器限制使用跨域脚本。如果您是服务器的维护者,请阅读Access-Control-Allow-Origin了解如何在您的网站上启用跨站点脚本。
编辑:要检查外部网站是否关闭,您可以使用此方法。该外部网站需要有图像文件。大多数网站的根目录中都有一个名为favicon.ico
的文件。例如,http://www.google.com/是否在线。
var test = new Image();
//If you're sure that the element is not a JavaScript file
//var test = document.createElement("script");
//If you're sure that the external website is reliable, you can use:
//var test = document.createElement("iframe");
function rmtmp(){if(tmp.parentNode)tmp.parentNode.removeChild(tmp);}
function online(){
//The website is likely to be up and running.
rmtmp();
}
function offline(){
//The file is not a valid image file, or the website is down.
rmtmp();
alert("Something bad happened.");
}
if (window.addEventListener){
test.addEventListener("load", online, true);
test.addEventListener("error", offline, true);
} else if(window.attachEvent){
test.attachEvent("onload", online);
test.attachEvent("onerror", offline);
} else {
test.onload = online;
test.onerror = offline;
}
test.src = "http://www.google.com/favicon.ico?"+(new Date).getTime();
/* "+ (new Date).getTime()" is needed to ensure that every new attempt
doesn't get a cached version of the image */
if(/^iframe|script$/i.test(test.tagName)){
test.style.display = "none";
document.body.appendChild(test);
}
这只适用于图片资源。阅读评论以了解如何使用其他来源。
这不是跨站点脚本。这只是将一个网站的内容加载到一个JavaScript变量中。此外,我无法访问服务器端代码。我只能在客户端进行更改。我试图访问的网站是外部的。 – Sunny
跨域*脚本。如果您的网站在http://foo.com上托管,并且在http://bar.com上提供了“外部源”,则相同来源策略会阻止您访问该源。无论您是使用框架还是XMLHttpRequest。您从外部网站获取JavaScript变量的唯一**选项是使用''来包含它们,前提是这些变量是有效的JavaScript变量。 –
那么,有没有办法将跨域的静态内容加载到JavaScript中的变量中?我试着看着dojo.io.iframe。他们似乎完成了这一点,但我找不到任何有用的例子。以下是dojo.io.iframe的链接:http://dojotoolkit.org/reference-guide/dojo/io/iframe.html – Sunny
试试这个:
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djConfig="parseOnLoad:true"></script>
<script>
dojo.require("dojo.io.script");
</script>
<script>
dojo.addOnLoad(function(){
dojo.io.script.get({
url: "http://badlink.google.com/",
//url: "http://www.google.com/",
load: function(response, ioArgs) {
//if no (http) error, it means the link works
alert("yes, the url works!")
}
});
});
</script>
PHP?的file_get_contents(yourTargetURL)?然后用ajax调用该web服务... –
我无法使用php。所有我被允许使用的是html和javascript。除此之外,我还可以使用JavaScript的dojo库。或者任何谷歌API也会有所帮助。 – Sunny