我尝试了w3schools的以下代码。当我在输入txt框中输入字母时,应相应地显示建议。但是,没有任何内容显示为建议。我无法通过序列化获取txt值。 在gethint.php中,由于它是一个post请求,我改变了原来的$ q = $ _ GET [“q”];到$ q = $ _ POST [“q”]。 有人能告诉我我做错了什么吗?谢谢。
post_example.html
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keyup(function(){
// txt=$("input").val();
txt=$("input").serialize();
$.post("gethint.php",txt,function(result){
$("span").html(result);
});
});
});
</script>
</head>
<body>
<p>Start typing a name in the input field below:</p>
First name:
<input type="text" >
<p>Suggestions: <span></span></p>
</body>
</html>
gethint.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=$_POST["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
答案 0 :(得分:1)
输入没有名称,所以当你serialize
时,你会得到一个空字符串。
答案 1 :(得分:1)
我认为你错过了,行中的q
$.post("gethint.php",txt,function(result){
应该是
$.post("gethint.php", {q: txt},function(result){
或者如果您使用serialize
,请使用输入框的名称,如
<input type="text" name="q" >