萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

jQuery $.get() 依下拉選單動態載入資料庫功能說明

功能簡介

使用者從下拉選單選擇程式語言,前端透過 $.get() 非同步向後端請求該語言對應的 API 函數說明,無需重整頁面即可顯示結果。展示 AJAX 提升使用者體驗的典型應用。

資料庫結構

CREATE TABLE language (
    id INT(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    languageName VARCHAR(50) NOT NULL
);

CREATE TABLE functions (
    id INT(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    languageId INT(11) NOT NULL,
    functionName VARCHAR(64) NOT NULL,
    summary VARCHAR(128) NOT NULL,
    example TEXT NOT NULL
);

前端 index.php 關鍵片段

<select id="selectLanguage">
    <option value="">select</option>
    <?php while($row = $result->fetch_assoc()) { ?>
        <option value="<?= $row['id'] ?>"><?= $row['languageName'] ?></option>
    <?php } ?>
</select>
<p id="result"></p>

<script>
$(function() {
    $('#selectLanguage').change(function() {
        var val = $(this).val();
        if (!val) return;
        $.get('results.php', {id: val}, function(data) {
            $('#result').html(data);
        });
    });
});
</script>

後端 results.php

<?php
$mysqli = new mysqli('localhost', 'root', 'passwd', 'exampledb');
$id = (int)$_GET['id'];
$query = "SELECT functionName, summary, example FROM functions WHERE languageId = $id";
$resultStr = '';
if ($res = $mysqli->query($query)) {
    if ($res->num_rows > 0) {
        $resultStr .= '
    '; while ($row = $res->fetch_assoc()) { $resultStr .= "
  • {$row['functionName']}-{$row['summary']}"; $resultStr .= "
    {$row['example']}
  • "; } $resultStr .= '
'; } else { $resultStr = 'Nothing found'; } } echo $resultStr; ?>

$.get() 參數速查

$.get(url, [data], [callback], [type])
// url: 請求網址
// data: 查詢字串物件 {key: value}
// callback: 成功時回呼 function(data)
// type: 回傳格式 xml, html, script, json, text, _default
copyright © 萬盛學電腦網 all rights reserved