1

我正在处理一个为主页设计的 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
4

2 回答 2

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.");
    }
} 

您也可以使用onreadystatechangeevent 而不是onload. 点击查看更多参考

于 2013-08-06T10:45:37.150 回答
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.");
    }
} 

参考

于 2013-08-06T11:38:56.553 回答