单击时使用 jQuery 和 AJAX 更改页面内容

Change page contents with jQuery and AJAX on click

本文关键字:AJAX jQuery 单击      更新时间:2023-09-26

我有一个简单的网页,上面有以下HTML

    <!doctype html>
    <html>
        <head>
            <title>Homework 8 - Home</title>
            <meta charset="utf-8">
            <link rel="stylesheet" type="text/css" href="style.css" />
            <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
            <script src="script.js"></script>
        </head>
        <body>
        <nav>
            <ul>
                <li><a href="home.html">Home</a></li>
                <li><a href="about.html">About</a></li>
                <li><a href="help.html">Help</a></li>
            </ul>
        </nav>
        <div id="content">
            <div id="page">
                Suspendisse vel ante ornare, vulputate lacus et, condimentum lorem.
            </div>
            <aside>
                <h3>Helpful Links</h3>
                <ul>
                    <li><a href="http://google.com/">Google</a></li>
                    <li><a href="http://facebook.com/">Facebook</a></li>
                </ul>
            </aside>
        </div>
        </body>
    </html>

以及以下php文件中的数据数组:

    <?php

    function random_lipsum($amount = 1, $what = 'paras', $start = 0) {
        return simplexml_load_file("http://www.lipsum.com/feed/xml?amount=$amount&what=$what&start=$start")->lipsum;
    }

    $data = [
        'home' => ['title' => 'Home page', 
                   'content' =>     random_lipsum(3),
                   'links' => [
                        'http://google.com/' => 'Google',
                        'http://facebook.com/' => 'Facebook',
                    ]
        ],
        'about' => ['title' => 'About page', 
                   'content' =>     random_lipsum(3),
                   'links' => [
                        'http://abv.bg/' => 'ABV.BG',
                        'http://dir.bg/' => 'DIR.BG',
                    ]
        ],
        'help' => ['title' => 'Help page', 
                   'content' =>     random_lipsum(3),
                   'links' => [
                        'http://wikipedia.com/' => 'Wikipedia',
                        'http://stackoverflow.com/' => 'StackOverflow',
                    ]
        ],
    ];
    $page = (isset($_GET['page']) && isset($data[$_GET['page']]))?$_GET['page']:'home';
    echo json_encode($data[$page]);
    ?>

我的任务是通过单击<nav>中的链接来更改<div id="content">页面<title>的内容以及jQueryAJAX <aside>的链接,而无需重新加载页面。例如,当您单击链接"关于"时,页面的内容、标题和旁置链接应更改为带有键aboutphp文件中data数组中的链接。我试图编写一些代码,但没有任何反应。这是它(它存储在一个名为script.js的文件中,该文件在HTML文件的<head>中引用(:

    $(document).ready(function(){   //executed after the page has loaded
        $('nav ul li:nth-child(2) a').on('click',
            $.ajax({    //create an ajax request data.php
                type: "POST",
                url: "data.php",
                data: 'page=about',
                dataType: "html",   //expect html to be returned
                success: function(data){
                    $('#page').html(data.about.content);
                    $('title').html(data.about.title);
                    $('aside ul li:first-child a').html(data.about.links[0]);
                    $('aside ul li:nth-child(2) a').html(data.about.links[1]);
                }
            })
        );
    });

你能帮帮我,告诉我我做错了什么吗?

你的 PHP 返回的是 JSON,而不是 HTML。用:

dataType: "json"

要返回的唯一 HTML 位于 titlecontent 属性的值中。此外,links元素中的 PHP 关联数组将成为 Javascript 对象,而不是数组。我建议你把它改成索引数组:

'links' => [
    [ 'url' => 'http://abv.bg/', 'name' => 'ABV.BG'],
    [ 'url' => 'http://dir.bg/', 'name' => 'DIR.BG']
]

那么success函数将是:

success: function(data) {
    $('#page').html(data.about.content);
    $('title').html(data.about.title);
    $.each(data.about.links(function(i, link) {
        $('aside ul li').eq(i).children('a').attr('href', link.url).html(link.name);
    });
}

正如 GolezRol 的回答中所指出的,.on()的处理程序参数必须是一个函数:

$('nav ul li:nth-child(2) a').on('click', function(e) {
    e.preventDefault();
    $.ajax(...);
});

由于您是从本地主机加载页面,因此您需要更改jQuery URL才能转到Web:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
省略 URL 的协议

前缀时,它使用与包含该 URL 的页面相同的协议,对于本地文件,该协议file: .但是你需要使用http:https:从网上获取一些东西。

您需要将需要

在单击时执行的代码包装在函数中,否则 Ajax 请求将在加载页面时立即执行,并且该调用的结果(这是一个 jqXHR 对象(将传递给.on()而不是 propert 回调。

  $(document).ready(function(){   //executed after the page has loaded
        $('nav ul li:nth-child(2) a').on('click',
          function() {
            $.ajax({    //create an ajax request data.php
                type: "POST",
                url: "data.php",
                data: 'page=about',
                dataType: "html",   //expect html to be returned
                success: function(data){
                    $('#page').html(data.about.content);
                    $('title').html(data.about.title);
                    $('aside ul li:first-child a').html(data.about.links[0]);
                    $('aside ul li:nth-child(2) a').html(data.about.links[1]);
                }
            })
          }
        );
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>