从HTML页面的url获取文档对象

时间:2013-08-06 10:41:50

标签: javascript jquery html

我正在开发一个专为主页设计的js文件。 我想通过导航菜单栏从此页面导航到其他页面。 目标页面共享相同的模板(html代码),因此,为了转到特定页面,我需要加载特定内容,该内容保存在xml文件中,然后将其内容传递到目标页面。

function loadFileToElement(filename, elementId)
{
  var xhr = new XMLHttpRequest();
  try
  {
    xhr.open("GET", filename, false);
    xhr.send(null);
  }
  catch (e) {
    window.alert("Unable to load the requested file.");
   }
  // Until this point I can load the specific content
  // How can I get from the url of the target page
  // a js document object, so that I can call getElementById(Id)
  // to pass the specific content.
  // For instance: Im currently opnening X1:= www.main.com 
  // und I would like to switch to X2 := www.targetpage.com 
  // target page which contains html the templat.
  //  The problem **document** represents currently X1
  // but i would like to set it to X2 so that I can pass
  // the content of xhr.responseText to it
  var component = **document**.getElementById(elementId);
  component.innerHTML = xhr.responseText;
  } 

Thanks

2 个答案:

答案 0 :(得分:0)

试试这个,我添加了xhr.onload函数,该函数填充了从响应中返回的文本

function loadFileToElement(filename, elementId)
{
    var xhr = new XMLHttpRequest();
    try
    {
        xhr.open("GET", filename, false);
        xhr.onload = function () {
            var component = document.getElementById(elementId);
            component.innerHTML = xhr.responseText;
        }
        xhr.send(null);
    }
    catch (e) {
        window.alert("Unable to load the requested file.");
    }
} 

您还可以使用onreadystatechange事件代替onloadclick for more reference

答案 1 :(得分:0)

试试这个

function loadFileToElement(filename, elementId)
{
    var xhr = new XMLHttpRequest();
    try
    {
        xhr.open("GET", filename, false);
        xhr.onload = function () {
            var com = document.getElementById(elementId);
            com.innerHTML = xhr.responseText;
        }
        xhr.send();
    }
    catch (e) {
        window.alert("Unable to load the requested file.");
    }
} 

Reference