Ajax和PHP在同一页面 - 我收到错误

时间:2013-06-03 06:22:33

标签: php ajax

我收到此错误

Notice: Undefined index: q in C:\wamp\www\FLEX\test1.php on line 50

<!DOCTYPE html>
<html>
<head>
<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("POST","test1.php?q="+str,true);
 xmlhttp.open("GET","<?php $_SERVER[PHP_SELF]; ?>
 ?q="+str,true);
 xmlhttp.send();
 }
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>


<?php
// Fill up array with names
echo $_GET["q"];
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
//get the q parameter from URL
$q=$_GET["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 个答案:

答案 0 :(得分:2)

在这里使用isset

if(isset($_GET["q"])) {
     $q=$_GET["q"];
     // rest of your code
}

这不是错误的通知警告。