AJAX调用后Php结果未显示


Php results not showinf after AJAX call

我必须创建此网页用于房地产交易。我正在使用ajax在同一页面上显示结果。。用户可以输入,但结果没有显示。。。也没有错误消息。。plz帮助。。。我是Ajax和PHP的新手。

html代码为:

Enter City :<input class="w-input" id="city"   type="text" placeholder="Enter the city name (required)" name="city" data-name="city" required="required" onchange="showUser(this.value)">
<div id="txtHint"><b>Results will be displayed Here...</b></div>

ajax代码:

<script>
function showUser(str) {
if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
} else { 
    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","buyresult.php?q="+str,true);
    xmlhttp.send();
}
}
</script>

最终buyresult.php文件内容

 <html>
 <head>
 <title></title>
 <link rel="stylesheet" type="text/css" href="form/style.css" />
 </head>
 <body>
 <?php
 include 'connection.php';
 SESSION_START();
 $q = intval($_GET['q']);
 $sql="SELECT * FROM property WHERE city = '".$q."'";
 $qry = mysql_query($sql) or die(mysql_error());
 while($result=mysql_fetch_array($qry))
 {
    echo '<h2 class="flat-heading">FLAT Id = '.$result['id'];
 }
 ?>
 </body>
 <script>
function showUser(str) {
    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","buyresult.php?q="+str,true);
    xmlhttp.send();
}
</script>

我认为问题出在

document.getElementById("txtHint").innerHTML = "";

这部分。。你可能没有定义这个id的任何位置。。。而不是得到

 $q = intval($_GET['q']);

使用

 $q = mysql_real_escape_string($_GET['q']);

我认为您的buyresult.php代码应该是这样的:

您的主要问题是您在查询中使用$q = intval($_GET['q']);并添加"",所以问题在您的查询中。请尝试下面的一个。它应该对你有用。

<html>
 <head>
 <title></title>
 <link rel="stylesheet" type="text/css" href="form/style.css" />
 </head>
 <body>
 <?php
 include 'connection.php';
 SESSION_START();
 $q   = intval($_GET['q']);
 $sql = "SELECT * FROM property WHERE city = $q";
 $qry = mysql_query($sql) or die(mysql_error());
 while($result=mysql_fetch_array($qry))
 {
    echo '<h2 class="flat-heading">FLAT Id = '.$result['id'];
 }
 ?>
 </body>