javascript - 单击链接时使用 AJAX 替换内容

标签 javascript php jquery ajax

我想使用 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/

相关文章:

javascript - 在 js/jquery 中选择框作为按钮

PHP/MYSQL - 需要更好的方法来处理此全文搜索查询

php - 如何制作选定列表/菜单项的数组

javascript - Jquery mousedown/mouseup 防止点击

JavaScript 全局对象?

javascript - 限制在 jQuery Photowall 中显示的照片数量

javascript - 如何将一个参数从一个函数传递给另一个函数

php - 创建随机字符串,检查数据库,如果发现再次运行 - 代码未按我的预期运行?

javascript - 将 php json 转换为 javascript getJSON

javascript - 如何删除javascript视差中页面末尾留下的额外空间