3

我的项目是在我的网站内预览一些网站,我现在使用 iframe 来加载网站预览,然后用户可以在 iframe 内进行交互。

我必须将 Iframe 实现更改为在页面内出于 SEO 目的,所以可以替代的是 Jquery .load() 函数。

$('div#websitePreview').load('Website_URL');

但问题是当用户与网站交互(单击某个链接)时,整个页面将重定向到新链接,所以有没有办法通过 ajax 调用加载用户在同一个 div 中单击的页面而不离开我的网站?

更新: 我要预览的网站有我原始网站的子域

4

3 回答 3

3

There is no way to achieve this, due cross domain security restrictions in modern browsers. You aren't allowed to access other domains content via ajax.

The other point is, that you may have css bugs if you load an entry page in a div on your site, because the loaded css will override your site's css.

于 2013-06-24T08:43:34.330 回答
1

Assuming the websites you are 'previewing' are on the same domain as your website, you can amend every a tag within the loaded div to perform an AJAX request with the following code:

var $container = $('#websitePreview')
$container.load('http://www.example.com'); // initial load

// link click within loaded content.
$container.on('click', 'a', function(e) {
    e.preventDefault();
    $container.load($(this).attr('href'));
});

On the other hand, if the previewed sites are on separate domains, you cannot load HTML from them due to the Same Origin Policy. An iframe or CORS request is your only option in those situations, and if the url is 3rd party, the latter is extremely unlikely to happen.

于 2013-06-24T08:43:01.397 回答
0

try

$('div#websitePreview a').live('click', function(event){
   event.preventDefault();
   var url = $(this).attr('href');
   $('div#websitePreview').load(url);
}
于 2013-06-24T08:41:16.963 回答