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