JavaScript >> Javascript 文檔 >  >> Tags >> CSS

一個簡單的帶有 jQuery 的 AJAX 網站

簡介

這次我們將使用 jQuery 和適量的 PHP &CSS 創建一個簡單的 AJAX 網站。它將有一些由 AJAX 從 PHP 後端加載的頁面,並且對瀏覽器歷史記錄的完整支持 - 對於任何 AJAX 或 Flash 站點來說都是一個真正的痛苦。

所以獲取演示文件 讓我們開始滾動吧。

XHTML

首先,我們創建站點的 XHTML 主幹。

demo.html

<div id="rounded">

<img src="img/top_bg.gif" /><!-- image with rounded left and right top corners -->
<div id="main" class="container"><!-- our main container element -->

<h1>A simple AJAX driven jQuery website</h1> <!-- titles -->
<h2>Because simpler is better</h2>

<ul id="navigation"> <!-- the navigation menu -->
<li><a href="#page1">Page 1</a></li> <!-- a few navigation buttons -->
<li><a href="#page2">Page 2</a></li>
<li><a href="#page3">Page 3</a></li>
<li><a href="#page4">Page 4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li> <!-- rotating gif - hidden by default -->
</ul>

<div class="clear"></div> <!-- the above links are floated - we have to use the clearfix hack -->

<div id="pageContent"> <!-- this is where our AJAX-ed content goes -->
Hello, this is the default content
</div>

</div>

<div class="clear"></div> <!-- clearing just in case -->

<img src="img/bottom_bg.gif" /> <!-- the bottom two rounded corners of the page -->

</div>

此代碼位於 body 中 我們的 demo.html 的一部分 文件。它的主要目的是作為 php 後端的前端,由 jQuery 處理其間的所有通信。

注意導航鏈接的地址 - #page 和頁碼。這部分,稱為 hash , 包含在當前 URL 中,無需刷新頁面,在瀏覽器的歷史記錄中創建一個條目。通過使用 javascript 監控這個哈希,我們可以通過 AJAX 更改加載的頁面並提供無縫的瀏覽體驗。

CSS

讓我們看看我們的樣式表。

demo.css

body,h1,h2,h3,p,td,quote,
small,form,input,ul,li,ol,label{    /* resetting our page elements */
    margin:0px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
}

body{   /* styling the body */
    margin-top:20px;
    color:#51555C;
    font-size:13px;
    background-color:#123456;
}

.clear{ /* the clearfix hack */
    clear:both;
}

a, a:visited {  /* styling the links */
    color:#007bc4;
    text-decoration:none;
    outline:none;
}

a:hover{    /* the hover effect */
    text-decoration:underline;
}

#rounded{   /* the outermost div element */
    width:800px;
    margin:20px auto;   /*center it on the page*/
}

.container{ /* this one contains our navigation, titles, and fetched content */
    background-color:#FFFFFF;
    padding:10px 20px 20px 20px;
}

h1{ /* the heading */
    font-size:28px;
    font-weight:bold;
    font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;
}

h2{ /* the subheading */
    font-weight:normal;
    font-size:20px;

    color:#999999;
}

ul{ /* the unordered list used in the navigation */
    margin:30px 0px;
}

li{ /* we float the li-s, which contain our navigation links - we later apply clearfix */
    list-style:none;
    display:block;
    float:left;
    width:70px;
}

li a,li a:visited{  /* the navigation links */
    padding:5px 10px;
    text-align:center;
    background-color:#000033;
    color:white;

    -moz-border-radius:5px; /* rounding them */
    -khtml-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:5px;

}

li a:hover{
    background-color:#666666;
    text-decoration:none;
}

#pageContent{   /* the container that holds our AJAX loaded content */
    margin-top:20px;

    border:1px dashed #cccccc;
    padding:10px;

    -moz-border-radius: 5px;    /* rounding the element */
    -khtml-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}

#loading{   /* hiding the rotating gif graphic by default */
    visibility:hidden;
}

一個重要的提醒是,只有最新版本的 Firefox 支持使用 CSS 圓角 , SafariChrome .

jQuery 源碼

為了補充前端,這裡是驅動站點的腳本。

script.js

$(document).ready(function(){ //executed after the page has loaded

    checkURL(); //check if the URL has a reference to a page and load it

    $('ul li a').click(function (e){    //traverse through all our navigation links..

            checkURL(this.hash);    //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)

    });

    setInterval("checkURL()",250);  //check for a change in the URL every 250 ms to detect if the history buttons have been used

});

var lasturl=""; //here we store the current URL hash

function checkURL(hash)
{
    if(!hash) hash=window.location.hash;    //if no parameter is provided, use the hash value from the current address

    if(hash != lasturl) // if the hash value has changed
    {
        lasturl=hash;   //update the current hash
        loadPage(hash); // and load the new page
    }
}

function loadPage(url)  //the function that loads pages via AJAX
{
    url=url.replace('#page','');    //strip the #page part of the hash and leave only the page number

    $('#loading').css('visibility','visible');  //show the rotating gif animation

    $.ajax({    //create an ajax request to load_page.php
        type: "POST",
        url: "load_page.php",
        data: 'page='+url,  //with the page number as a parameter
        dataType: "html",   //expect html to be returned
        success: function(msg){

            if(parseInt(msg)!=0)    //if no errors
            {
                $('#pageContent').html(msg);    //load the returned html into pageContet
                $('#loading').css('visibility','hidden');   //and hide the rotating gif
            }
        }

    });

}

請注意,在第 3 行,我們如何調用 checkURL() 頁面加載完成後立即運行 - 這樣我們可以確保,如果指向網站內部頁面的鏈接已被共享並且新訪問者訪問它,則該網站將獲取所需的頁面並在頁面加載時顯示它.

正如你在第 11 行看到的,我們為 checkURL() 設置了一個間隔 每秒檢查瀏覽器地址 4 次,以檢測使用後退/前進按鈕可能引起的任何變化。

現在讓我們看看後端。

PHP

PHP 後端只是幾行代碼,如果您想自定義此示例,則可以從這裡開始。

load_file.php

if(!$_POST['page']) die("0");

$page = (int)$_POST['page'];

if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');

else echo 'There is no such page!';

它基本上檢查變量 $POST['page'] 已設置,如果已設置,則檢查相應的 page.html 文件存在,並輸出回jQuery。

您可以通過從數據庫中獲取數據、使用會話或顯示圖像文件夾來改進這一點 - 您可能想到的任何東西。

結論

今天,我們創建了一個簡單的、可定制的、支持 AJAX 的網站。隨意使用您在任何項目中展示的代碼和技術。


Tutorial JavaScript 教程
  1. 火星車

  2. 在自定義(非本機)組件上使用 v-tooltip

  3. 您最近發佈到公共存儲庫的軟件包?

  4. MERN 堆棧 TODO 應用程序

  5. 在反應應用程序上更改文檔標題

  6. 閱讀片段 [11]

  7. 處理 JavaScript 中的特定錯誤(想想異常)

  1. 關係運算符(第 1 部分)

  2. Internet Explorer 7 – 遊戲狀態

  3. FullStack 前端:Firebase 簡介(Firebase v9)

  4. #SeasonsOfServerless - 加入我們的節日開發者挑戰賽!

  5. ReactJS — 適合初學者的視角 — 第一部分

  6. 幫助我的瀏覽器 API 在 Angular Universal 中停止工作

  7. 為什麼 JavaScript 的 parseInt 的基數默認為 8?

  1. 我是如何(不小心)用 Vanilla JS 從零開始製作遊戲引擎的

  2. Cypress 使用 TypeScript 對 React 組件進行單元測試

  3. 在 Vue 中創建可重用的選項卡組件

  4. 如何在跨瀏覽器擴展中操作 webRequest cookie?