我是 JavaScript 新手,正在尝试使用一些 Ajax 将 HTML 动态加载到<div>
元素中。我有一个 PHP 页面,它会吐出一个 JSON,其中包含插入<div>
. 我一直在测试,无法接听电话。我开始在我的就绪状态上发出警报,我得到 0,然后什么也没有。根据我的理解,sendData()
每次readystate更改时都应该调用该函数,但它似乎只执行一次,或者readystate永远不会改变,所以它只被调用一次......?
这是我的 PHP
<?php
$array['html'] = '<p>hello, menu here</p>';
header('Content-type: application/json');
echo json_encode($array);
?>
这是我的 HTML
<!DOCTYPE html>
<html>
<head>
<title>Veolia Water - Solutions and Technologies Dashboard</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta name="description" content="Veolia Water - Dashboard"/>
<meta http-equiv="imagetoolbar" content="no" />
<meta author="Nathan Sizemore"/>
<link rel="stylesheet" href="./css/stylo.css" media="screen"/>
</head>
<body>
<div id="menu">
</div>
<div id="content">
</div>
</body>
<script src="./js/dashboard.js"></script>
</html>
这是我的 JavaScript
var request;
window.onload = function()
{
load_menu();
}
//Load menu function
function load_menu()
{
request = getHTTPObject();
alert(request.readyState);
request.onreadystatechange = sendData();
request.open("GET", "./php/menu.php", true);
request.send(null);
}
function getHTTPObject()
{
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xhr = false;
}
}
}
return xhr;
}
function sendData()
{
alert(request.readyState);
// if request object received response
if (request.readyState == 4)
{
var json = JSON.parse(request.responseText);
document.getElementById('menu').innerHTML = json.html;
alert(json.html);
}
}
提前感谢您的帮助!
弥敦道