【发布时间】:2022-01-12 20:42:04
【问题描述】:
我是 Ajax 和 jQuery 的新手,问题是我有一个文件夹页面,其中是带有内容 div 的 php 页面。我想用内容而不是整个页面重新加载容器 div 我尝试了很多东西,但似乎没有任何帮助。这是我的 index.php 外观的一部分:
<?php include ('inc/nav.php'); ?>
<div id="container">
<?
$type = $_GET["type"];
switch ($type) {
case "about" :
include "pages/about-us.php";
break;
case "contact":
include "pages/contact.php";
break;
default :
include "pages/homepage.php";
}
?>
</div>
在导航中,链接如下所示:
<ul class="main-menu">
<li class="url"><a href="index.php?type=homepage">Homepage</a></li>
<li class="url"><a href="index.php?type=about-us">About us</a></li>
<li class="url"><a href="index.php?type=contact">Contact</a></li>
</ul>
我试图将 pages/about-us.php 中的内容放入 <div id="container"></div>,但它不起作用。这就是我的 ajax 脚本的样子:
//run on page load
$(function(){
//bind a click event to the nav links
$(".url a").on("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
console.log(pageLocation);
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#container").html(data.responseText);
}
});
});
});
【问题讨论】:
-
您将在拉入 dom 时释放任何附加的 js 事件,但要回答
$("#container").html($(data.responseText).find('#container')); -
欢迎来到 Stack Overflow。 从 jQuery 3.0 开始,
.bind()已被弃用。自 jQuery 1.7 起,它已被用于将事件处理程序附加到文档的.on()方法取代,因此已不鼓励使用它。 请提供一个最小的、可重现的示例:stackoverflow.com/help/minimal-reproducible-example 最好也采用游览:stackoverflow.com/Tour -
@LawrenceCherone 我用你的答案更新了代码,但是当我加载页面时它变空了
-
@Twisty 我已经更新了我的代码并提供了一个最少的代码
-
@5admin 您在控制台中看到任何错误吗?请求和响应是什么样的?