2011-09-21 52 views
1

這是我正在嘗試完成的: 獲取「外部」網址的靜態內容並檢查特定關鍵字,例如「用戶指南」或「未找到網頁」。如何在JavaScript變量中存儲網頁的靜態內容?

我試圖使用Ajax,dojo.xhr等,但他們不支持跨域。在我的情況下,它是一個外部網址。另外,我不能使用jQuery。

我也看過dojo.io.iframe,但我找不到有用的例子來完成這個。

dojo.io.iframe示例會非常有幫助。 請幫忙。

謝謝!

+0

PHP?的file_get_contents(yourTargetURL)?然後用ajax調用該web服務... –

+0

我無法使用php。所有我被允許使用的是html和javascript。除此之外,我還可以使用JavaScript的dojo庫。或者任何谷歌API也會有所幫助。 – Sunny

回答

1

現代瀏覽器限制使用跨域腳本。如果您是服務器的維護者,請閱讀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); 
} 

這隻適用於圖片資源。閱讀評論以瞭解如何使用其他來源。

+0

這不是跨站點腳本。這只是將一個網站的內容加載到一個JavaScript變量中。此外,我無法訪問服務器端代碼。我只能在客戶端進行更改。我試圖訪問的網站是外部的。 – Sunny

+1

跨域*腳本。如果您的網站在http://foo.com上託管,並且在http://bar.com上提供了「外部源」,則相同來源策略會阻止您訪問該源。無論您是使用框架還是XMLHttpRequest。您從外部網站獲取JavaScript變量的唯一**選項是使用''來包含它們,前提是這些變量是有效的JavaScript變量。 –

+0

那麼,有沒有辦法將跨域的靜態內容加載到JavaScript中的變量中?我試着看着dojo.io.iframe。他們似乎完成了這一點,但我找不到任何有用的例子。以下是dojo.io.iframe的鏈接:http://dojotoolkit.org/reference-guide/dojo/io/iframe.html – Sunny

0

試試這個:

<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> 
相關問題