JavaScript >> Javascript 文檔 >  >> jQuery

教程:製作一個由 Google 提供支持的購物搜索網站

在本教程中,我們將製作一個簡單的產品搜索引擎。使用 jQuery 和 PHP,我們將利用 Google 的購物搜索 API 並返回可供購買的商品列表,以及價格、照片和其他有用信息。購物搜索 API 讓我們可以直接訪問從合作在線商店獲得的 Google 龐大的產品和價格數據庫。使用這項服務的另一個好處是,產品會在後台自動為我們進行排名和過濾,以更好地匹配用戶的搜索查詢。

讓我們開始編碼吧!

HTML

與往常一樣,第一步是設置頁面的 HTML 佈局。我們將使用一個簡單的 HTML5 文檔,您可以在下面看到:

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Google Product Search | Tutorialzine Demo</title>

        <!-- CSS Includes -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans+Condensed:700" />
        <link rel="stylesheet" href="assets/css/styles.css" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <header>
            <h1>Product Search</h1>

            <form action="" method="get">
                <input type="text" id="q" name="q" placeholder="what do you want to buy?" />
                <img id="preload" alt="preload" src="assets/img/325.gif"/>
            </form>

            <h2>Powered by <b>Google</b></h2>
        </header>

        <section id="products">
            <!-- The product list will go here -->
        </section>

        <p id="message">
            <!-- Error messages will be displayed here -->
        </p>

        <!-- JavaScript includes -->
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>

這裡沒有什麼太令人興奮的事情。我們有一個包含單個文本字段的表單,即 products 部分,將保存購物項目和一個消息 當什麼都沒有找到時顯示。這是一個購物清單項目的標記(它將由jQuery根據api調用的結果生成):

<a class="product" data-price="$73.99" href="http://ebay.com/..." target="_blank">
    <img alt="eBay" src="http://i.ebayimg.com/.." />
    <span>eBay</span>
</a>

完成此操作後,我們現在可以繼續生成 Google API 密鑰。

獲取 Google API 密鑰

Google 免費提供其 API,但我們必須為我們的應用程序生成一個唯一密鑰才能使用它。這有助於他們跟踪使用情況並驗證每個請求。我們之前做過這個,當時我們用谷歌構建一鍵式註冊表單,這次沒有太大不同。您需要做的是訪問 Google 的 API 控制台並設置一個新項目,然後激活 Search API for Shopping;這將為您提供我們將在下一節中使用的 API 密鑰(請閱讀此處了解有關步驟的更多詳細信息)。

請注意,Google 對每個密鑰的 API 請求數施加了限制。購物搜索 api 每天只允許 2500 次免費請求,所以如果你打算用它做一些嚴肅的事情,你可能需要付費。

編寫代理

為了安全通信,並保持您的 API 密鑰私密,我們必須通過服務器上的 PHP 腳本路由我們的請求。雖然 API 返回 JSON 格式的數據,但我們不能在不暴露我們的密鑰的情況下直接從 JavaScript 中使用它(並且不違反同源策略)。

這個 PHP 腳本或代理非常簡單:

proxy.php

// Enter your Google API key here
// you can obtain it from the API console
$key = 'YOUR API KEY GOES HERE';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search'])) {

    $search = urlencode($_POST['search']);
    $url = 'https://www.googleapis.com/shopping/search/v1/public/products?key=' . $key . '&country=US&q=' . $search . '&maxResults=24';

    echo file_get_contents($url);
}

該腳本從 $_POST 獲取輸入,對其進行編碼,然後將其發送給 Google,然後打印結果。

jQuery 代碼

現在我們已經準備好了一切,我們可以繼續編寫驅動我們的購物搜索引擎的 jQuery 代碼:

assets/js/script.js

$(document).ready(function(){

    var saveTimer,
        searchBox = $('#q'),
        products =  $('#products'),
        message = $('#message'),
        preloader = $('#preload');

    preloader.css('visibility','hidden');

    searchBox.on('input',function(e){

        // Clearing the timeout prevents
        // saving on every key press
        clearTimeout(saveTimer);

        // If the field is not empty, schedule a search
        if($.trim(searchBox.val()).length > 0) {
            saveTimer = setTimeout(ajaxProductsSearch, 2000);
        }
    });

    $('form').submit(function(e){
        e.preventDefault();

        if($.trim(searchBox.val()).length > 0) {
            clearTimeout(saveTimer);
            ajaxProductsSearch();
        }
    });

    function ajaxProductsSearch(){

        products.empty();
        preloader.css('visibility','visible')

        // Issue a request to the proxy
        $.post('proxy.php', {
            'search' : searchBox.val()
        },
        function(data) {

            if(data.totalItems == 0){

                preloader.css('visibility','hidden');
                message.html("We couldn't find anything!").show();
                return false;
            }

            $.each(data.items, function(i, item){

                var html = ' <a class="product" data-price="$ '+item.product.inventories[0]['price']+'" href="'+item.product['link']+'" target="_blank">';

                // If the product has images
                if(item.product.images && item.product.images.length > 0){
                    html += '<img alt="'+item.product.author['name']+'" src="'+ item.product.images[0]['link']+'"/>';
                }

                html+='<span>'+item.product.author['name'].substr(0, 20)+'</span></a> ';

                products.append(html);
            });

            preloader.css('visibility','hidden');

        },'json');
    }

});

我正在使用幾週前在 AJAX 筆記教程中使用的相同超時技巧。通過在未來兩秒設置超時並在每次按鍵時清除它,我們可以僅在用戶停止輸入時運行搜索。

這樣我們的產品搜索網站就完成了!

這是一個包裝!

您可以使用產品搜索 API 來使用訪問者感興趣的相關產品來增強您現有的 Web 應用程序。該 API 為您提供了比此處顯示的更多的功能 - 您可以過濾、排序和分組結果、應用拼寫檢查和顯示統計信息。您甚至可以加入 google 的聯盟網絡並從您的應用程序中賺取真金白銀。


Tutorial JavaScript 教程
  1. 無代碼 - 沒有後端 開發人員的表單發送器 發送您的 <form> 沒有後端

  2. Chrome 擴展教程:如何從頁面上下文傳遞消息

  3. 提升你的變量! (JavaScript 中的變量提升)

  4. Node.js – 將路由端點快速路由到數組內的對象鍵值

  5. 什麼是代理模式?以及如何通過 JavaScript 實現它?

  6. 使用 React 在 1 個文件中構建一個簡單的博客

  7. 如何使用按鈕清除語義 UI React 中的多選下拉菜單?

  1. 使用 ES6 生成器實現異步

  2. window.location.href 更改時的事件

  3. 在 React 中創建汽車遊戲 - 第 3 部分 - 碰撞

  4. Calm Technology - CTA 火車跟踪器

  5. 徵求意見:Quirk,一個開源的認知行為治療應用程序

  6. 檢測和跟踪您在生產中的錯誤並修復它!

  7. 過濾 Google App Script 的 html 部分中的表格

  1. 回到 HTML、CSS 和 JavaScript 並用大約 200 行良好的舊代碼構建一個演講者網站

  2. 我使用 Reactjs、WebRTC 和 Chakra UI 創建了 Web Gallery 應用程序

  3. Ruby 像芭蕾舞一樣優雅

  4. JavaScript 面試問題 #17:兩個空數組之和