蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

AJAX 实时搜索

核对实时搜索(Live Search)渐进过滤优势、前端 onkeyup 与边框联动、PHP DOMDocument 配合 stristr 匹配链接列表及输出转义实测。

学完这一章,你能够

  • 核对实时搜索(Live Search)渐进过滤优势、前端 onkeyup 与边框联动、PHP DOMDocument 配合 stristr 匹配链接列表及输出转义实测。

实时搜索的交互优势与前端 showResult() 流程

AJAX 实时搜索(Live Search)允许用户在输入关键词的同时即时浏览候选条目,相比传统提交表单搜索具备三项优势:键入即显匹配结果、继续输入自动收窄范围、删除字符立即放宽结果。示例数据源为存放少量页面标题与链接的 `links.xml`(演示集含 6 条链接,输入 `HTML` 即可过滤出相关条目)。

前端输入框绑定 `onkeyup="showResult(this.value)"`:当 `str.length == 0` 时清空 `#livesearch` 内容并把边框设为 `0px` 后退出;输入非空时创建 `XMLHttpRequest`、设置就绪回调(写入响应并显示 `1px solid #A5ACB2` 边框),随后将输入内容作为参数 `q` 发送至 `livesearch.php?q=`。来源页嵌入式 `<script>`、`<form>` 与 `<input>` 已静态登记且不执行。

PHP 检索 links.xml 与安全输出实测

后端 `livesearch.php` 在 `strlen($q) > 0` 时通过 `DOMDocument` 载入 `links.xml`,遍历所有 `<link>` 节点提取 `<title>` 与 `<url>`,使用不区分大小写的 `stristr()` 判断标题是否包含 `$q`:匹配到的条目拼装为 `<a href='...' target='_blank'>...</a>` 并以 `<br />` 分隔累加到 `$response`,若无任何命中则返回 `"no suggestion"`。生产代码须对取出的 URL 与标题调用 `htmlspecialchars(..., ENT_QUOTES, 'UTF-8')` 防范标记破坏与 XSS。本站 PHP 8.4.27 实测 6 条目录 XML:`html` 与 `HTML` 返回完全一致的 `3` 条链接(含 2 个 `<br />`);连续键入 `H` -> `HTML` -> `HTML DOM` 命中数逐级收窄为 `4 -> 3 -> 1`;未命中 `GraphQL` 与空串均返回 `no suggestion`;含 `&` 与 `<Guide>` 的特殊标题被安全转义输出。

运行 PHP 8.4 AJAX 实时搜索大小写无关匹配、渐进过滤与 XSS 转义实测

含完整源码 · 141 行
展开查看收起
php
<?php
declare(strict_types=1);

$cases = [];

function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
    $cases[] = [
        'name' => $name,
        'passed' => ($actual === $expected),
        'expected' => $expected,
        'actual' => $actual,
    ];
}

$linksXml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<pages>
  <link>
    <title>HTML a tag</title>
    <url>https://example.org/html/tag-a</url>
  </link>
  <link>
    <title>HTML br tag</title>
    <url>https://example.org/html/tag-br</url>
  </link>
  <link>
    <title>HTML DOM Document</title>
    <url>https://example.org/dom/document</url>
  </link>
  <link>
    <title>CSS background Property</title>
    <url>https://example.org/css/background</url>
  </link>
  <link>
    <title>PHP Date() Function</title>
    <url>https://example.org/php/date</url>
  </link>
  <link>
    <title>JavaScript Array Object</title>
    <url>https://example.org/js/array</url>
  </link>
</pages>
XML;

$tmpFile = tempnam(sys_get_temp_dir(), 'live_links_');
if ($tmpFile === false) {
    throw new RuntimeException('Failed to create temp file');
}

$liveSearch = static function (string $xmlPath, string $q): string {
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($xmlPath);
    $links = $xmlDoc->getElementsByTagName('link');
    $hint = '';

    if (strlen($q) > 0) {
        for ($i = 0; $i < $links->length; $i++) {
            $titles = $links->item($i)->getElementsByTagName('title');
            $urls = $links->item($i)->getElementsByTagName('url');
            if ($titles->length > 0 && $urls->length > 0 && $titles->item(0)->nodeType === XML_ELEMENT_NODE) {
                $titleVal = $titles->item(0)->childNodes->item(0)?->nodeValue ?? '';
                $urlVal = $urls->item(0)->childNodes->item(0)?->nodeValue ?? '';
                if (stristr($titleVal, $q) !== false) {
                    $anchor = "<a href='" . htmlspecialchars($urlVal, ENT_QUOTES, 'UTF-8')
                        . "' target='_blank'>" . htmlspecialchars($titleVal, ENT_QUOTES, 'UTF-8') . '</a>';
                    $hint = ($hint === '') ? $anchor : ($hint . '<br />' . $anchor);
                }
            }
        }
    }
    return $hint === '' ? 'no suggestion' : $hint;
};

try {
    file_put_contents($tmpFile, $linksXml);

    // Case 1: Case-insensitive search for "html" and "HTML"
    $resLower = $liveSearch($tmpFile, 'html');
    $resUpper = $liveSearch($tmpFile, 'HTML');
    add_case(
        $cases,
        'livesearch_case_insensitive_html',
        [
            'case_insensitive_equal' => true,
            'match_count' => 3,
            'has_br_separator' => true,
        ],
        [
            'case_insensitive_equal' => ($resLower === $resUpper),
            'match_count' => substr_count($resLower, '<a href='),
            'has_br_separator' => (substr_count($resLower, '<br />') === 2),
        ]
    );

    // Case 2: Progressive narrowing & widening when typing/deleting characters
    $c1 = substr_count($liveSearch($tmpFile, 'H'), '<a href=');
    $c2 = substr_count($liveSearch($tmpFile, 'HTML'), '<a href=');
    $c3 = substr_count($liveSearch($tmpFile, 'HTML DOM'), '<a href=');
    add_case(
        $cases,
        'livesearch_narrowing_filter',
        ['count_h' => 4, 'count_html' => 3, 'count_html_dom' => 1],
        ['count_h' => $c1, 'count_html' => $c2, 'count_html_dom' => $c3]
    );

    // Case 3: Unmatched query and empty query return "no suggestion"
    add_case(
        $cases,
        'livesearch_no_suggestion',
        ['unmatched' => 'no suggestion', 'empty' => 'no suggestion'],
        ['unmatched' => $liveSearch($tmpFile, 'GraphQL'), 'empty' => $liveSearch($tmpFile, '')]
    );

    // Case 4: Escaped special characters in XML title/url prevent broken markup
    $specialXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><pages><link>"
        . "<title>HTML &amp; CSS &lt;Guide&gt;</title>"
        . "<url>https://example.org/search?a=1&amp;b=2</url>"
        . "</link></pages>";
    $tmpSpecial = tempnam(sys_get_temp_dir(), 'live_esc_');
    try {
        file_put_contents($tmpSpecial, $specialXml);
        $escapedRes = $liveSearch($tmpSpecial, 'Guide');
    } finally {
        if ($tmpSpecial !== false && is_file($tmpSpecial)) {
            unlink($tmpSpecial);
        }
    }
    add_case(
        $cases,
        'livesearch_xss_safe_output',
        "<a href='https://example.org/search?a=1&amp;b=2' target='_blank'>HTML &amp; CSS &lt;Guide&gt;</a>",
        $escapedRes
    );
} finally {
    if (is_file($tmpFile)) {
        unlink($tmpFile);
    }
}

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
验证 html/HTML 均命中 3 条链接、H->HTML->HTML DOM 渐进收窄为 4->3->1、无匹配返回 no suggestion 及特殊字符正确 HTML 转义。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1224.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

应在前端对 onkeyup 回调加入防抖(debounce,如停顿 200-300ms 再发请求),并使用 AbortController 或请求序号丢弃过期的旧响应,避免高频击键压垮服务端或造成结果乱序覆盖。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习