我的ajax脚本在一个div中加载我的整个index.php站点

时间:2013-01-17 01:38:44

标签: php javascript mysql ajax

我创建了一个简单的文本输入框,用于使用ajax从数据库中获取数据。

<form method="post" action="">
        <input type="text" id="txt1" onkeyup="showHint(this.value);" />
</form>

文本框在我的ajax.js文件中调用一个名为showHint(str)的ajax函数,如下所示:

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","index.php?page=getList&q="+str,true);
xmlhttp.send();

}

从上面的脚本可以看出,它打开了我的PHP脚本,用于从数据库中获取详细信息,如下所示:

    //get the q parameter from URL
$q = $_GET["q"];

$sql = "SELECT Name FROM Country WHERE Name LIKE '" . $q . "%'";

$recordSet = $_dbConn->query($sql);
$a = $recordSet->getrow();

 //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;

问题是我使用的是单个Index.php页面,所以这一行:“index.php?page = getList&amp; q =”+ 有点像说www.mydomain.com/index.php?index.php?page=getLet$q。

我该如何解决这个问题?我试过使用POST但仍然没有工作。我也试图擦除JS中的index.php部分,也不会工作......谢谢

1 个答案:

答案 0 :(得分:0)

根据@ lethal-guitar - xmlhttp.open(“GET”,“/ index.php?page = getList&amp; q =”+ str,true);