JavaScript包括另一个文件

时间:2014-01-19 16:57:11

标签: javascript php file menu include

我有这段代码:

var curState = 'Agenda';

function switchState(newState) {
  curState = newState;
}

function Inbox() {
  switchState('Inbox');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Inbox.";
}

function Friends() {
  switchState('Friends');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Friends.";
}

function Agenda() {
  switchState('Agenda');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Agenda.";
}

function List() {
  switchState('List');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Book List.";
}

function News() {
  switchState('News');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the News.";
}

function Notes() {
  switchState('Notes');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Notes.";
}

当然显示的文字是一个测试,我会更改它。关键是,我必须在菜单的这些“状态”中加入大量文本,并在此处简单地输入它并不是很方便,特别是如果稍后要进行更改。因此,我想知道如何在JavaScript中添加不同形式的文件,或者让它们使用JavaScript显示,如* .php文件。

有谁知道怎么做这样的事情?我在互联网上搜索了很多,但找不到对我有用的东西,除了document.getElementById().innerHTML = "";

1 个答案:

答案 0 :(得分:1)

有三种简单的方法可以做到这一点:

变体A:通过AJAX调用从服务器获取innerHTML - 类似于

function News() {
  switchState('News');
  document.getElementById("u-content").innerHTML = "Please wait for News to load.";
  //start AJAX call here
}

function AJAXcallOnSuccess() {
  document.getElementById("u-content").innerHTML = //Result text from AJAX call;
}

变式B:您的文字已在原始页面中传送,但未显示。像

这样的东西
<blah>
... 
<div style="display: none;" id="newsPlaceHolder">
This is the text for the news item
</div>
...
</blah>

function News() {
  switchState('News');
  document.getElementById("u-content").innerHTML = document.getElementById("newsPlaceHolder").innerHTML
}

变体B导致最简单的变体C:在页面中准备好所有DIV,但一次只显示一个。

var activeDiv = null;

function News() {
  switchState('News');
  if (activeDiv) activeDiv.style.display='none';
  activeDiv=document.getElementById("u-content-news");
  activeDiv.style.display='block';
}