2012-03-27 71 views
0

我试过了w3schools的以下代码。当我在输入文本框中输入字母时,应该相应地显示建议。但是,没有任何东西被显示为建议。我无法通过序列化获取txt值。 在gethint.php中,由于它是一个post请求,我改变了原来的$ q = $ _ GET [“q”];到$ q = $ _ POST [“q”]。 有人能告诉我我做错了什么吗?谢谢。ajax jquery php:w3school示例jquery ajax后不显示暗示

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; 
?> 
+1

试试这个'' – safarov 2012-03-27 05:55:06

+2

你真的应该停下来使用w3schools网站。由于“为什么”的原因,请阅读:http://w3fools.com/ – 2012-03-27 05:58:21

回答

1

我想你错过了,在q在你行

$.post("gethint.php",txt,function(result){ 

应该

$.post("gethint.php", {q: txt},function(result){ 

,或者如果你正在使用serialize然后使用输入框的名称,如

<input type="text" name="q" > 
+0

是的,工作。非常感谢。 :) – vaanipala 2012-03-27 06:09:41

+0

好吧,你的第二个解决方案(用于序列化)的工作,但它不工作时,我使用txt = $(“输入”)。和$ .post(“gethint.php?q =”。txt,函数(结果){ – vaanipala 2012-03-27 06:15:40

+0

@vaanipala感谢提醒我现在检查更新的代码,这将工作.. – 2012-03-27 06:22:26

1

输入没有名字,所以当你serialize它,你得到一个空字符串返回。