我想使用 AJAX 来替换 div 的内容。尽管该应用程序相当复杂,但我已尝试将其孤立地简化,以便我可以首先使基本概念起作用。
现在,我只想根据 PHP 文件替换一个 div ......
<?php
$id = $_GET['id'];
if ($id = 1)
{
$text = 'This is some text';
}
elseif ($id = 2) {
{
$text = 'This is a lot more text than the first text!';
}
elseif ($id = 3) {
{
$text = 'This is a lot more text than the first text, and a load more than the third as well!!';
}
echo $text;
?>
相当简单的东西真的。所以这是我的HTML文件......
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">I want this content replacing</div>
<a href="#" onclick="loadXMLDoc()">ID: 1</a><br>
<a href="#" onclick="loadXMLDoc()">ID: 2</a><br>
<a href="#" onclick="loadXMLDoc()">ID: 3</a>
</body>
</html>
我意识到,因为我已经修改了我在网上找到的一些东西,所以那里永远不会起作用,但基本上我希望将链接中的 ID 等变量传递给 AJAX 脚本来替换 div 的内容。
我如何让这个工作?有没有比使用<a>
标签更好的选择?