【发布时间】:2014-06-11 10:17:16
【问题描述】:
按照http://www.w3schools.com/ajax/ajax_aspphp.asp 的示例,我正在使用 php 文件发回与数组中的单词相关的建议。我想在 html 中显示它们,但是当我将段落标记放在 php 文件周围时,整个数组被打印到屏幕上而不是选定的单词,请帮助我的 javascript 代码,表格如下
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
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("txtHint").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","gethint.php",true);
xmlhttp.send();
}
</script>
然后是我的 PHP 文件
<?PHP
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// get the q parameter from URL
$q=$_REQUEST["q"];
$hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{ $q=strtolower($q); $len=strlen($q);
foreach($a as $name)
{ if (stristr($q, substr($name,0,$len)))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= ", $name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
【问题讨论】:
-
这些段落标签到底在哪里?
-
我把它们放在整个 php 文件中只是为了看看它会做什么,但我知道这是错误的
-
响应中实际返回了什么? (即
xmlhttp.onreadystatechange函数中xmlhttp.responseText的值是多少?)id="txtHint"的元素是什么?该元素中没有设置内容吗? -
所以您只需在整个 PHP 代码周围添加段落?想知道为什么这不起作用!
-
对不起,我是新手,但是当我在 firefox 中使用 firebug 时,整个文件都会在响应中返回
标签: javascript php html ajax