繁体   English   中英

如何在javascript变量中存储网页的静态内容?

[英]How do I store static content of a web page in a javascript variable?

这就是我要完成的工作:获取“外部” URL的静态内容,并检查其中的某些关键字,例如“用户指南”或“找不到页面”。

我尝试使用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);
}

这仅适用于图像资源。 阅读评论,了解如何使用其他资源。

尝试这个:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM