使用Ajax更新页面的一部分,而不使用jQuery

Update portion of page using Ajax without jQuery

本文关键字:jQuery 一部分 更新 Ajax 使用      更新时间:2023-09-26

该页面大部分是PHP的,并且只少量使用任何JavaScript,因此我不希望在没有jQuery的情况下使用jQuery。我想更新页面的一部分,但我对Ajax不是很有经验。jQuery的方法是使用页面的URL后面带有"#sectionid"。

您需要了解的所有信息都可以在这里:

https://developer.mozilla.org/en/XMLHttpRequest

您将对文档的sendopenresponsereadyStateonreadystatechange部分感兴趣。

每当请求的就绪状态更改时,onreadystatechange都会触发。 将readyState更改为done后,您可以查看收到的回复。

确保打开时以异步模式打开。 您不希望通过发出同步 http 请求来冻结页面。

如果您需要它在旧版本的IE上运行,维基百科有一些很好的信息:http://en.wikipedia.org/wiki/XMLHttpRequest#Support_in_Internet_Explorer_versions_5.2C_5.5_and_6

我假设您知道如何使用document.getElementByIdelement.innerHTML来设置元素的内容。


编辑继续并添加了一个基本实现:

if (window.XMLHttpRequest) {// IE7+, Firefox, Webkit, Opera
  window.xmlhttp = new XMLHttpRequest();
} else {// IE6, 5
  window.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     document.getElementById("someId").innerHTML = xmlhttp.responseText;
  }
}
xmlhttp.open("GET", "pageUrl", true);
xmlhttp.send();