修改Ajax Live Search以包含一个新字段



https://www.w3schools.com/php/php_ajax_livesearch.asp

我正在尝试修改教程中ajax实时搜索的代码,以包含一个名为keyword的新字段。我希望搜索也能搜索关键字字段,以提高用户体验。

我已经修改了link.xml fine以包含新添加的关键字标记。

<link>
<title> title </title>
<keyword> keywords here </keyword>
<url>https://path to url</url>
</link>

我有点困在下面的区域,试图修改条件语句。

<?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>0
if (strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$k=$x->item($i)->getElementsByTagName('keyword'); // New field added 
$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 was found
// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}
//output the response
echo $response;
?>

我认为你可以更改条件

if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))

$checkTitle = stristr($y->item(0)->childNodes->item(0)->nodeValue,$q);
$checkKeyword = stristr($k->item(0)->childNodes->item(0)->nodeValue,$q);
if ($checkTitle || $checkKeyword) {
//
}

最新更新