jQuery/Ajax 将外部页面加载到内容 div 中

jQuery/Ajax 将外部页面加载到内容 div 中

问题描述:

我有一个网站,我不想将外部 html 内容加载到我的 index.html <div id="content"> 而不必刷新页面.我设法用 jQuery load() 函数来做到这一点.当我阅读 load()ajax() 时,我了解到 ajax 是一个比加载更可配置的函数,但基本上做同样的事情(如果我错了纠正我*).当我使用 load() 时,外部内容会加载,但 url 地址不显示当前页面.因此,我想问一下是否有人可以告诉我我该怎么做:

I have a website that i wan't to load external html content into my index.html <div id="content"> without having to refresh the page. I manage to do this with jQuery load() function. When i read up on load() and ajax(), it has come to my understanding that ajax is a more configurable function then load, but do basically the same thing (correct me if im wrong*). When I use load() the external content loads but the url address doesn't show the current page. Therefore I want to ask if someone out there can show me how i can:

  • 使 ajax() 函数的行为类似于 load().

  • Make the ajax() function behave like load().

动态显示并在 url 中获取 href 以用于书签等

Show dynamically and fetch href in url for bookmark etc.

Ajax() 代码示例:https://plnkr.co/edit/ReSdd5U6dOYbQxctzvk7?p=preview

Ajax() code example: https://plnkr.co/edit/ReSdd5U6dOYbQxctzvk7?p=preview

Load() 代码示例:https://plnkr.co/edit/gpsZbOip0VtO7iXTPaM2?p=preview

Load() code example: https://plnkr.co/edit/gpsZbOip0VtO7iXTPaM2?p=preview

有问题吗?问!

先谢谢了!

/E.

据我所知,您希望使用 jQuery load() 或等效的 AND浏览器历史记录(地址栏)更新以反映刚刚加载的内容的 url.

As I understand it, you are looking to use jQuery load() or an equivalent AND have the browser history (address bar) update to reflect the url of the just loaded content.

既然您建议让 load() 工作,那么您所追求的是浏览器 History_API,特别是 pushState().

Since you suggest that you have load() working, then what you are after is the browser History_API, specifically pushState().

您可以阅读有关以下内容的更多信息:History_API

You can read more about the : History_API

您还可以阅读以下内容:pushState() 方法

You can also read about the : pushState() method

根据您的 load() 示例,我认为您可以使用以下内容对其进行扩展以获得所需的内容:

Based on your load() example, I think you can extend it with the following to get what you are after:

$('#content').load('link1.html');
$('a').click(function(e){
  var page = $(this).attr('href');
  $('#content').load(page + '.html');

  var stateObj = {loaded : page};
  history.pushState(stateObj, "page title", page + '.html');

  return false; // don't follow the link
});

您还可以查看 Mozilla 的基于 AJAX 的导航示例 做我认为您希望通过 AJAX 而不是 jQuery 做的事情,并使用 pushstate.

You can also see Mozilla's AJAX based navigation example that does what I think you are looking to do via AJAX rather than jQuery and uses pushstate.