PHP 和 AJAX Live Search
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>
正如你看到的,HTML 页面包含一个简单的 HTML 表单,其中的文本框名为 "txt1"。
表单是这样工作的:
当用户在文本框中按键并松开按键时,会触发一个事件 当事件触发时,会执行名为 showResult() 的函数 表单下面是名为 "livesearch" 的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;}
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;?>
如果从 JavaScript 送来了任何文本 (strlen($q) > 0),会发生:
PHP 创建 "links.xml" 文件的一个 XML DOM 对象 遍历所有 "title" 元素 (nodetypes = 1),以便找到匹配 JavaScript 所传数据的 name 找到包含正确 title 的 link,并设置为 "$response" 变量。如果找到多于一个匹配,所有的匹配都会添加到变量 如果没有找到匹配,则把 $response 变量设置为 "no suggestion" $result 是送往 "livesearch" 占位符的输出
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.
