Home Backend Development PHP Tutorial PHP 和 AJAX Live Search

PHP 和 AJAX Live Search

Jun 23, 2016 pm 02:34 PM

AJAX 可为用户提供更友好、交互性更强的搜索体验。

AJAX Live Search

在下面的 AJAX 例子中,我们将演示一个实时的搜索。

实时的搜索与传统搜索相比,具有很多优势:

当键入数据时,就会显示出匹配的结果 当继续键入数据时,对结果进行过滤 如果结果太少,删除字符就可以获得更宽的范围

在下面的文本框中搜索 W3School 的页面

本例包括四个元素:

简单的 HTML 表单 JavaScript PHP 页面 XML 文档

在本例中,结果在一个 XML 文档 (links.xml) 中进行查找。为了让这个例子小而简单,我们只提供 8 个结果。

HTML 表单

这是 HTML 页面。它包含一个简单的 HTML 表单,针对此表单的 CSS 样式,以及指向 JavaScript 的链接:

<html><head><script src="livesearch.js"></script> <style type="text/css"> #livesearch  {   margin:0px;  width:194px;   }#txt1  {   margin:0px;  } </style></head><body><form><input type="text" id="txt1" size="30"onkeyup="showResult(this.value)"><div id="livesearch"></div></form></body></html>
Copy after login
例子解释 - HTML 表单

正如你看到的,HTML 页面包含一个简单的 HTML 表单,其中的文本框名为 "txt1"。

表单是这样工作的:

当用户在文本框中按键并松开按键时,会触发一个事件 当事件触发时,会执行名为 showResult() 的函数 表单下面是名为 "livesearch" 的
元素。它用作 showResult() 所返回数据的占位符

JavaScript

JavaScript 代码存储在与 HTML 文档连接的 "livesearch.js" 中:

var xmlHttpfunction showResult(str){if (str.length==0) {  document.getElementById("livesearch"). innerHTML=""; document.getElementById("livesearch"). style.border="0px"; return }xmlHttp=GetXmlHttpObject()if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return }var url="livesearch.php"url=url+"?q="+strurl=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)} function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  document.getElementById("livesearch"). innerHTML=xmlHttp.responseText; document.getElementById("livesearch"). style.border="1px solid #A5ACB2"; } }function GetXmlHttpObject(){var xmlHttp=null;try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { // Internet Explorer try  {  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");  } catch (e)  {  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  } }return xmlHttp;}
Copy after login
例子解释:

GetXmlHttpObject 与 PHP 和 AJAX 请求 中的例子相同。

showResult() 函数

该函数每当一个字符输入文本框就会执行一次。

如果文本域中没有输入 (str.length == 0),该函数把返回字段设置为空,并删除周围的任何边框。

不过,如果文本域中存在输入,则函数执行:

定义发送到服务器的 url (文件名) 把带有输入框内容的参数 (q) 添加到 url 添加一个随机数,以防止服务器使用缓存文件 调用 GetXmlHttpObject 函数来创建 XMLHTTP 对象,并在触发一个变化时告知此函数执行名为 stateChanged 的一个函数 使用给定的 url 来打开 XMLHTTP 对象 向服务器发送 HTTP 请求 stateChanged() 函数

每当 XMLHTTP 对象的状态发生变化时,该函数就会执行。

当状态变为 4 (或 "complete") 时,就会使用响应文本来填充 txtHint 占位符的内容,并在返回字段周围设置一个边框。

PHP 页面

由 JavaScript 代码调用的服务器页面是名为 "livesearch.php" 的 PHP 文件。

"livesearch.php" 中的代码检查那个 XML 文档 "links.xml"。该文档 w3school.com.cn 上的一些页面的标题和 URL。

这些代码会搜索 XML 文件中匹配搜索字符串的标题,并以 HTML 返回结果:

<?php$xmlDoc = new DOMDocument();$xmlDoc->load("links.xml");$x=$xmlDoc->getElementsByTagName('link');//get the q parameter from URL$q=$_GET["q"];//lookup all links from the xml file if length of q>0if (strlen($q) > 0){$hint="";for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1)  {  //find a link matching the search text  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))   {   if ($hint=="")    {    $hint="<a href='" .     $z->item(0)->childNodes->item(0)->nodeValue .     "' target='_blank'>" .     $y->item(0)->childNodes->item(0)->nodeValue . "</a>";    }   else    {    $hint=$hint . "<br /><a href='" .     $z->item(0)->childNodes->item(0)->nodeValue .     "' target='_blank'>" .     $y->item(0)->childNodes->item(0)->nodeValue . "</a>";    }   }  } }}// Set output to "no suggestion" if no hint were found// or to the correct valuesif ($hint == "") { $response="no suggestion"; }else { $response=$hint; } //output the responseecho $response;?>
Copy after login
例子解释:

如果从 JavaScript 送来了任何文本 (strlen($q) > 0),会发生:

PHP 创建 "links.xml" 文件的一个 XML DOM 对象 遍历所有 "title" 元素 (nodetypes = 1),以便找到匹配 JavaScript 所传数据的 name 找到包含正确 title 的 link,并设置为 "$response" 变量。如果找到多于一个匹配,所有的匹配都会添加到变量 如果没有找到匹配,则把 $response 变量设置为 "no suggestion" $result 是送往 "livesearch" 占位符的输出
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles