我现在有一种方法,其中有一个实况搜索功能与JSON
<input type="text" id="politician" name="politician"
onkeyup="showResult(this.value)" value="Enter a politician's name"/>
标签。在包括输入的标签相同的文件中,有外部的链接的javascript称为ajax.js
该文件的内容文件中,如下所示:
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?politician="+str,true);
xmlhttp.send();
}
基本上,JavaScript文件做什么就是说,无论何时将值插入到输入文本框中,都会将请求发送到名为“livesearch.php”的php文件,该文件解析名为politicians.xml的硬编码XML文档的内容。
的livesearch.php文件如下:
<?php
//Make sure we have something set before we go doing work
if (isset($_GET["politician"])){
$q = $_GET["politician"];
if ($q == "")
exit();
$xmlDoc = new DOMDocument();
$xmlDoc->load("politicians.xml");
$x=$xmlDoc->getElementsByTagName('Politicians');
$hint = "";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('name');
$z=$x->item($i)->getElementsByTagName('url');
$w=$x->item($i)->getElementsByTagName('location');
$v=$x->item($i)->getElementsByTagName('position');
$u=$x->item($i)->getElementsByTagName('photo');
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 .= "<br />";
}
$hint .= "<h1 id='poli'><a id='blue' href='";
$hint .= $z->item(0)->childNodes->item(0)->nodeValue;
$hint .= "'>";
$hint .= $y->item(0)->childNodes->item(0)->nodeValue;
$hint .= "</a> <br /><a id='green'>";
$hint .= $v->item(0)->childNodes->item(0)->nodeValue;
$hint .= "</a><a id='green'>";
$hint .= $w->item(0)->childNodes->item(0)->nodeValue;
$hint .= "</a><br/><img width='30' height='40' id='schmidt' src='politicians/";
$hint .= $u->item(0)->childNodes->item(0)->nodeValue;
$hint .= ".png' /></h1>";
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if($hint == "")
echo "No suggestions";
else
echo $hint;
?>
我的一个朋友最近告诉我,JSON是XML的一个伟大的选择,因为使用JSON会少放应变的服务器上,因为它不会需要依靠PHP来解析XML文档的内容。客户端会解析它。
但是,我没有足够的JSON经验来重写此函数,以便它可以与JSON文档一起使用。任何人都可以给我一些提示吗?
任何帮助将不胜感激!
请将所有代码缩进至少四个空格,以便更易于阅读。 – ma11hew28 2010-10-22 23:57:32
如果您希望它们可见,您必须选择HTML代码作为代码... – 2010-10-23 00:04:51