我密切关注 AJAX 教程 ( https://www.youtube.com/watch?v=WwngGtboldU ),以了解如何防止加载网站的某些部分。您可以看到,在 17:50,他点击了链接,并且没有加载整个页面,而是仅加载了特定部分。
但是,它对我来说根本不起作用。当我单击“猫”或“狗”时,会加载整个页面。真是令人沮丧!有人能弄清楚我的版本可能出了什么问题吗?顺便说一句,我一直在使用 XAMPP,并且我总是通过打开 cats.php 或 dogs.php 来测试它。
样式.css
body{
background-color: aqua;
}
ul#nav {
list-style:none;
padding:0;
margin: 0 0 10px 0;
}
ul#nav li {
display:inline;
margin-right:10px;
}
标题.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>History API</title>
</head>
<body>
<nav id="main">
<ul>
<li><a href="cats.php">Cats</a></li>
<li><a href="dogs.php">Dogs</a></li>
</ul>
</nav>
页脚.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var nav, content, fetchAndInsert;
nav = $('nav#main');
content = $('section#content');
//Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data){
content.html(data);
}
});
});
//User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
nav.find('a').on('click', function(e) {
var href = $(this).attr('href');
//Manipulate history
history.pushState(null, null, href);
//Fetch and insert content
fetchAndInsert(href);
e.preventDefault();
});
});
</script>
</body>
</html>
猫.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/cats.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
内容/cats.php
Cats say meow
狗.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/dogs.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
内容/dogs.php
Dogs say woof
最佳答案
我认为您错过了最后一个正斜杠:
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
应该是
url: 'http://localhost/BlankApacheHistoryAPI/content/' + href.split('/').pop(),
关于javascript - 损坏的代码 -- 如何正确使用 AJAX 来阻止加载网站的这一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334637/