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

一個帶有 jQuery UI 的簡單電影搜索應用程序

在本教程中,我們使用 jQuery UI 的自動完成小部件來構建一個簡單的 AJAX 電影搜索表單。該腳本將使用 TheMovieDatabase.org 的免費 API,針對龐大的電影標題數據庫提供自動建議。

對於那些可能不熟悉 TMDb.org 的人來說,這是一個開放的、社區驅動的電影數據庫。它類似於您可能聽說過的 IMDb,但也為開發人員提供了許多有用的 API。

先決條件

在能夠使用 API 之前,您需要在快速註冊後從 TMDb 獲得免費的開發者密鑰。在此之後,記得將您的密鑰複製到 movieInfo.php 來自下載檔案。

第 1 步 - XHTML

標記由兩個主要的 div 容器組成 - #logo#holder .前者以透明PNG圖像(定義為各個div的背景)的形式保存圖標和徽標文本,而後者包含搜索表單和提交按鈕。

movieApp.html

<div id="page">

    <div id="logo">
        <div id="icon"></div>
        <div id="movieAppLabel"></div>
    </div>

    <div id="holder">
        <form action="http://www.themoviedb.org/search" method="post" target="_blank">
            <fieldset>
                <input type="text" id="movieName" name="search" />
            </fieldset>
        </form>
        <a href="#" class="button">Submit</a>
    </div>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script src="script.js"></script>

請注意,表單的 action 屬性指向 TMDB 的搜索頁面。搜索詞通過帶有 #movieName 的 POST 傳遞 文本域。您可以通過填寫電影名稱並提交表單來測試它。

最後在頁面中包含 jQuery、jQuery UI 和我們自己的腳本文件。我們正在使用 jQuery UI 的自動完成小部件來顯示從 TMDb 的 API 獲取的電影標題的下拉列表。您可以看到下面的小部件生成的標記。

<input class="ui-autocomplete-input"/>
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all">
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 1</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 2</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 3</a>
  </li>
</ul>

此代碼由小部件自動生成並附加在結束正文標記之前。

第 2 步 - PHP

當您開始在表單的文本框中輸入電影標題時,會向 moveInfo.php 發送 AJAX 請求 .該腳本使用我們的開發人員密鑰向 TMDb 的 API 發送搜索請求。該服務返回一個帶有合適電影標題的 JSON 對象。腳本處理它們並將它們作為對 AJAX 請求的響應輸出。

讓我們仔細看看它是如何工作的。

movieInfo.php

/**
 *  Define your API key below. To obtain one, visit
 *  http://www.themoviedb.org/account/signup
 */

$api_key = '...';

// If the request was not issued by AJAX, or
// the search term is missing, exit:

if(!$_SERVER["HTTP_X_REQUESTED_WITH"] || !$_GET['term']){
    exit;
}

include 'tmdbAPI/TMDb.php';

$tmdb = new TMDb($api_key);

// Send a search API request to TMDb,
// and parse the returned JSON data:

$json = json_decode($tmdb->searchMovie($_GET['term']));

$response = array();

$i=0;
foreach($json as $movie){

    // Only movies existing in the IMDB catalog (and are not adult) are shown

    if(!$movie->imdb_id || $movie->adult) continue;
    if($i >= 8 ) break;

    // The jQuery autocomplete widget shows the label in the drop down,
    // and adds the value property to the text box.

    $response[$i]['value'] = $movie->name;
    $response[$i]['label'] = $movie->name . ' <small>(' . date('Y',strtotime($movie->released)).')</small>';
    $i++;
}

// Presenting the response as a JSON object:

echo json_encode($response);

幸運的是,有一個 PHP 類可用,它處理與 TMDb API 的所有通信。我們只需要將它包含到頁面中,並提供我們從 TMDb 收到的開發者 API 密鑰。用戶在搜索框中輸入的搜索詞可在 $_GET['term'] 中找到 .調用 searchMovie() 使用這些術語的方法,將產生一個 JSON 對象,其中包含與我們的搜索條件匹配的電影的各種信息。您可以在下面看到一個示例響應。

[{
    "score": 8.750235,
    "popularity": 3,
    "translated": true,
    "adult": false,
    "language": "en",
    "name": "The Hitchhiker's Guide to the Galaxy",
    "alternative_name": "The Hitchhikers Guide to the Galaxy",
    "movie_type": "movie",
    "id": 7453,
    "imdb_id": "tt0371724",
    "url": "http://www.themoviedb.org/movie/7453",
    "rating": 6.8,
    "certification": "PG",
    "overview": "Mere seconds before the Earth is to be demolished by an alien construction crew, Arthur Dent is swept off the planet by his friend Ford Prefect, a researcher penning a new edition of \"The Hitchhiker's Guide to the Galaxy.\"",
    "released": "2005-04-20",
    "posters": [{
        "image": {
            "type": "poster",
            "size": "original",
            "height": 1000,
            "width": 675,
            "url": "http://hwcdn.themoviedb.org/posters/16e/4bcc96cd017a3c0f2600016e/the-hitchhiker-s-guide-to-the-galaxy-original.jpg",
            "id": "4bcc96cd017a3c0f2600016e"
        }
    }],
    "version": 22,
    "last_modified_at": "2010-07-19 22:59:02"
}]

響應包含標題 電影,概述 , 發布日期 ,對應的 IMDB id,甚至 海報粉絲藝術 .我們不需要大部分此類信息,因此 PHP 僅將其簡化為標題和發布年份,然後以 JSON 對象的形式輸出,供自動完成功能使用。這將我們帶到了下一步。

第 3 步 - jQuery

如您所知,jQuery 以插件的形式提供了許多有用的功能。該庫還有一個專用擴展,用於構建用戶界面,稱為 jQuery UI。它為開發人員提供了可供使用且易於定制的小部件。其中一個小部件是新版本的庫中引入的新的自動完成小部件。

讓我們看看它是如何使用的。

script.js

$(document).ready(function(){

    // Caching the movieName textbox:
    var movieName = $('#movieName');

    // Defining a placeholder text:
    movieName.defaultText('Type a Move Title');

    // Using jQuery UI's autocomplete widget:
    movieName.autocomplete({
        minLength   : 5,
        source      : 'movieInfo.php'
    });

    $('#holder .button').click(function(){
        if(movieName.val().length && movieName.data('defaultText') != movieName.val()){
            $('#holder form').submit();
        }
    });
});

// A custom jQuery method for placeholder text:

$.fn.defaultText = function(value){

    var element = this.eq(0);
    element.data('defaultText',value);

    element.focus(function(){
        if(element.val() == value){
            element.val('').removeClass('defaultText');
        }
    }).blur(function(){
        if(element.val() == '' || element.val() == value){
            element.addClass('defaultText').val(value);
        }
    });

    return element.blur();
}

要創建自動完成,我們只需要調用 autocomplete() 方法。它需要一些可選參數。最重要的是 minLength (這可以防止在輸入一定數量的字符之前觸發對服務器的請求)和 source, 它決定了下拉列表中顯示的數據。

來源 可以採用帶有字符串的數組、URL(將向其發送 AJAX 請求)或回調函數。在我們的例子中,movieInfo.php 的 URL 就夠了。

這是一個示例響應,由 movieInfo.php 返回(此 JSON 對像是在向 TMDb 的 API 請求“Hitchhiker's guide”後編譯的 ")。

[{
    "value": "Hachiko: A Dog's Story",
    "label": "Hachiko: A Dog's Story <small>(2009)<\/small>"
},
{
    "value": "Teenage Hitch-hikers",
    "label": "Teenage Hitch-hikers <small>(1975)<\/small>"
},
{
    "value": "The Hitchhiker's Guide to the Galaxy",
    "label": "The Hitchhiker's Guide to the Galaxy <small>(2005)<\/small>"
},
{
    "value": "The Hitch-Hiker",
    "label": "The Hitch-Hiker <small>(1953)<\/small>"
}]

數組中的每個對像都包含一個 和一個標籤 財產。標籤只顯示在下拉列表中,而一旦選擇項目,值就會插入到文本框中。

第 4 步 - CSS

現在所有的標記都已經生成並就位了,是時候開始美化了。

styles.css - 第 1 部分

#page{
    width:600px;
    margin:150px auto 0;
}

/* Logo */

#logo{
    width:380px;
    position:relative;
    height:90px;
    margin:0 auto;
}

#icon{
    width:80px;
    height:86px;
    background:url('img/icon.png') no-repeat;
    float:left;
}

#movieAppLabel{
    width:268px;
    height:58px;
    background:url('img/logo_txt.png') no-repeat;
    position:absolute;
    right:0;
    top:18px;
}

/* The Search Box & Holder */

#holder{
    width:530px;
    height:145px;
    background:url('img/holder.png') no-repeat center center;
    margin:30px auto;
    position:relative;
}

#holder fieldset{
    position:absolute;
    top:52px;
    left:40px;
    border-bottom:1px solid #fff;
}

#holder input{
    font-family:'Myriad Pro',Arial,Helvetica,sans-serif;
    border:none;
    border-bottom:1px solid #bbb;
    background:none;
    color:#8D8D8D;
    font-size:20px;
    padding:4px 0;
    width:250px;
    text-shadow:1px 1px #fff;
    outline:none;
}

在代碼的第一部分,我們為 #logo 設置樣式 , 和 #holder 分區。快門圖標和徽標文本被定義為 #icon 的背景 和 #movieAppLabel div 分別。 #holder 應用相對定位 以便更容易定位輸入框和提交按鈕。

styles.css - 第 2 部分

fieldset{
    border:none;
}

/* The Blue Button */

a.button{
    background:url('img/buttons.png') no-repeat;
    width:105px;
    height:37px;
    position:absolute;
    top:52px;
    right:42px;
    text-indent:-9999px;
    overflow:hidden;
    border:none !important;
}

a.button:hover{
    background-position:left bottom;
}

/* Styling the markup generated by the autocomplete jQuery UI widget */

ul.ui-autocomplete{
    width:250px;
    background-color:#f5f5f5;
    border:1px solid #fff;
    outline:1px solid #ccc;
}

ul.ui-autocomplete li{
    list-style:none;
    border-bottom:1px solid #e0e0e0;
    border-top:1px solid #fff;
}

ul.ui-autocomplete li:first-child{
    border-top:none;
}

ul.ui-autocomplete li:last-child{
    border-bottom:none;
}

ul.ui-autocomplete li a{
    color:#999;
    border:none !important;
    text-decoration:none !important;
    padding:10px 17px;
    display:block;
}

#ui-active-menuitem{
    background-color:#fff;
    color:#666;
    cursor:pointer;
}

jQuery UI 確實有它自己的樣式,但是它們相當笨重並且不適合當前的設計。這就是為什麼我們要應用一些規則(從第 23 行開始),這些規則將自定義設計應用於自動完成小部件。小部件的結構基本上是一個無序列表,每個建議的項目都是 li 中的超鏈接 元素。考慮到這一點(在從第一步的代碼中查找適當的類名之後),我們可以安全地設置下拉列表的樣式並將其與設計的其餘部分完美融合。

有了這個我們的簡單電影搜索應用程序就完成了!

總結

您可以修改此腳本以使用任何類型的 api 和數據。這可能是一個強大的工具,因為它可以幫助用戶輸入他們通常不會想到的搜索詞。例如,提供您的產品名稱作為搜索建議,可能是展示更多商品和提高銷量的有效策略。

你怎麼看?您將如何改進此應用?


Tutorial JavaScript 教程
  1. 如何使用Javascript將簡單數組轉換為二維數組(矩陣)

  2. contenteditable 中的佔位符 - 焦點事件問題

  3. 將 html 加載到頁面元素中(chrome 擴展)

  4. 使用角度 2 的 http.get() 從本地文件加載 json

  5. 檢測項目中的死代碼

  6. 為什麼在 NodeJs 中需要 Helmet?

  7. screen.availHeight 和 window.height() 的區別

  1. 當URL中出現#時如何調用javascript函數

  2. JavaScript 提升新手指南

  3. GraphQL 中的圖形

  4. 嘗試過 TDD 並沒有意識到好處?下次遇到作家阻止時嘗試一下

  5. 返回 JavaScript 類值而不是對象引用

  6. 我是如何創建這些生成下劃線筆觸的

  7. 理解 Javascript 中的解構

  1. 為 JavaScript 項目創建 GitHub 構建

  2. SubmitHub 創始人談論建立一個沒有計算機學位的 7 位數公司

  3. 參加 27 日和 28 日的 Git Commit Show,享受價值 10 萬美元的贈品!

  4. 為什麼我使用 Quokka.js 進行原型設計?