将外部页面加载到DIV中

时间:2012-12-27 14:45:57

标签: jquery html jquery-load

此代码在IE中运行良好,但在Chrome中无效。 有人可以指出我正确的方向,让它在大多数当前的浏览器中运行。

单击链接时,应将页面加载到div中。 代码复制自: webdeveloper.com

<script>
function processAjax(url) {
      if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = targetDiv;
      try {
        req.open("GET", url, true);
      } catch (e) {
        alert(e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = targetDiv;
        req.open("GET", url, true);
        req.send();

      }
    }
}

function targetDiv() {
    if (req.readyState == 4) { // Complete
          if (req.status == 200) { // OK response
              document.getElementById("MyDivName").innerHTML = req.responseText;
          } else {
            alert("Problem: " + req.statusText);
          }
    }
}  
</script>


<a href="javascript:processAjax('test.html');">CLICK ME</a>
<div id="myDivName"></div>  

谢谢:)

1 个答案:

答案 0 :(得分:1)

在jQuery中你可以这样做:

$("#myDivName").load("test.html", function(response, status, xhr) {
   if (status == "error") {
      var msg = "Sorry but there was an error: ";
      alert(msg + xhr.status + " " + xhr.statusText);
   }
 });

看看:jQuery API load() function