【发布时间】:2010-10-22 23:49:42
【问题描述】:
我目前有一个方法,有一个
<input type="text" id="politician" name="politician"
onkeyup="showResult(this.value)" value="Enter a politician's name"/>
标签。在包含输入标记的同一个文件中,有一个指向名为 ajax.js 的外部 javascript 文件的链接
该文件的内容如下:
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 文件发送请求,该文件会解析硬编码的 XML 文档的内容,该文件名为 politics.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 文档一起使用。谁能给我一些建议?
任何帮助将不胜感激!
【问题讨论】:
-
请将所有代码缩进至少四个空格,以便于阅读。
-
如果你想让它们可见,你必须选择 HTML 标签作为代码......
标签: php javascript xml json