我想使用 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>
我意识到那里永远不会工作,因为我已经修改了一些我在网上找到的东西,但基本上我希望传递一个变量,例如 AJAX 脚本链接中的 ID 来替换 div 的内容.
我如何让它工作?有没有更好的替代方法来使用 <a>
标签?
最佳答案
使用jQuery
你的 HTML
<a href="#" class="ajax" data-id="1">ID: 1</a>
Javascript
// Delegate click event
$(document).on('click', 'a.ajax', function(){
var el = $(this);
$.ajax({
url: 'ajax.php',
data: {id: el.data('id')},
}).done(function(response){
$('#myDiv').html(response);
});
return false;
});
关于javascript - 单击链接时使用 AJAX 替换内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365822/