2013-08-26 99 views

回答

2

首先下載JS文件https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js並在您的頁面中包含js文件。以下是我用來加載外部頁面的功能。

function test() { 
    $.ajax({ 
     url: 'http://external_site.com', 
     type: 'GET', 
     success: function(res) { 
     var content = $(res.responseText).text(); 
     alert(content); 
     } 
    }); 
    } 

這適用於我從外部網站獲取內容。

Reference

+0

我之前嘗試過,它沒有工作:(。任何想法,我錯了嗎? – NoSense

+0

不幸的是,這並沒有把戲。 – NoSense

+0

對於後來的答案感到抱歉。 – NoSense

3

是的,看到http://api.jquery.com/load/ 「加載頁面片段」。

總之,你在URL後添加選擇器。例如:

$('#result').load('ajax/test.html #container'); 
+0

感謝您的回答,但這並不奏效。 – NoSense

0

您可以嘗試的iframe:根據崗位

<iframe src="http://en.wikipedia.org/wiki/Robert_Bales" frameborder="0"></iframe> 
+0

謝謝,但我只想獲得頁面某些元素的內容。感謝 – NoSense

1

您可以隨時使用CURL在PHP中,以從其他站點獲取內容,然後可以使用load()JQuery函數訪問PHP並將其顯示給該頁面上的用戶。 假設這個文件被命名爲:「gatherinfo.php」(JQuery無法從遠程站點收集信息,因爲它不安全,我相信(http://forum.jquery.com/topic/using-ajax-to-load-remote-url-not-working)),所以其中一種方法是通過PHP來完成。

<?php 
$myData = curl("http://en.wikipedia.org/wiki/Robert_Bales"); 
echo "$myData"; 

function curl($url) { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 
?> 

但是,確保您在收集這類信息時始終引用來源。 然後通過使用JQuery,你可以打電話給你的服務器上的文件和你想通過執行以下操作在div顯示它:

的Javascript:(這將讓初始化一次頁面已準備就緒,並已加載)

$(document).ready(function(){ 
    $("#yourDIVID").load("gatherinfo.php"); 
}); 

HTML:

<html> 
<head> 
<script src="yourjqueryfile.js" type="text/javascript"></script> 
<script type="text/javascript"> 
     $(document).ready(function(){ 
      $("#yourDIVID").load("gatherinfo.php"); 
     }); 
</script> 
</head> 
<body> 
<div id="yourDIVID"> The content you're grabbing would load here </div> 
</body> 
</html> 

這是你會怎麼做,如果這是你打算做什麼。

+0

,但是如何獲得某個元素的內容? – NoSense

+0

好吧,我加: $(「#getPrice」)。load(「gatherinfo.php #content」);但id似乎不起作用。任何想法,我錯了? – NoSense

+1

向我們顯示您的HTML。 Hashtags(#)用於指向id,而點(。)用於指向元素的類。我會爲你編輯我的答案,並且也會爲你做javascript函數。 –

相關問題