蓝色天空网mbsky.com · 知识 · 实践 · 创造PHP · 本地阅读预览
教程 / 后端开发 / PHP

AJAX 实时搜索

核对实时搜索(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 转义实测

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 转义。
运行 PHP 8.4 AJAX 实时搜索大小写无关匹配、渐进过滤与 XSS 转义实测

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

当前源码 SHA256:8c9ccbf7e9adc4990a23be0344bd4ded3355f92e1fbec96f237269c5841b0cd1

下载本站示例源码

本地运行

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

下载AJAX 实时搜索实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

ZIP SHA256:011a76a0430cc0f6738e9805173a4cfe0649eabab98b56a25272cc2b6450cc68

常见错误与边界

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

练习与解答

在高频 onkeyup 实时搜索场景下,除了后端的 stristr 过滤与输出转义,前端通常还应采取什么优化措施?

展开参考解答

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

规范与官方依据