我使用AJAX实现了动态创建HTML表格。
这是我创造的:
的index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="ContactController.js">
</script>
</head>
<body>
<div class="main-wrapper">
<div id="menu">
<a href="javascript:void(0)" onclick="getAllContacts()">
Go to contacts
</a>
</div>
<div id="main-content">
</div>
</div>
</body>
</html>
ContactsController.js
function getAllContacts() {
// Manage new XmlHttpObject creation
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null);
}
function stateChanged() {
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
document.getElementById("main-content").innerHTML = xmlHttp.responseText;
}
}
// Creates a new XmlHttpObject
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// XmlHttpObject constructor for Chrome, Firefox, Opera, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v6.0
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v5.5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
getAllContacts.php
<?php
include 'connectToMySQL.php';
$command = "SELECT * FROM contact";
$result = mysql_query($command);
echo "<table id='contactsTable' border='1'>";
// Table headers
echo "<tr>
<th>Name</th>
</tr>";
// Print all contacts
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='#'
onclick=\"getContact('" . $row['DisplayName'] . "')\">"
. $row['DisplayName'] .
"</a>
</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
因此,点击Go to contacts
链接可激活getAllContacts
javascript功能。该函数调用getAllContacts
php函数,该函数从MySQL数据库中检索数据并将其放在contactsTable
表中。
我需要告诉函数将该表放在main-content
页面中的index.php
div中。我该如何实现这一目标?谢谢。
答案 0 :(得分:1)
好的,所以从你关于想要两个不同的可能目标div的评论开始,只需定义你的onreadystatechange事件内联并使用局部变量来引用div ...
function getAllContacts() {
// Manage new XmlHttpObject creation
var xmlHttp = GetXmlHttpObject(); // MAKE THIS LOCAL INSTEAD OF GLOBAL!
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
var targetDiv = document.getElementById(whateverIdYouWant);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = function(){
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
targetDiv.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(null);
}