2012-08-08 106 views
2

我正在嘗試創建AJAX搜索並遇到一些困難。這是我的JS和形式:AJAX搜索未顯示結果

<script type="text/javascript">// 
function prodSearch(request) { 

    if (request == "") { 
     document.getElementById("searchResults").innerHtml=""; 
     return; 
    } 

    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } 

    xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readystate==4 && xmlhttp.status==200) { 
      document.getElementById("searchResults").innerHTML=xmlhttp.responseText; 
     } 
    } 
xmlhttp.open("GET","/ps.php?country="+request,true); 
xmlhttp.send(); 
} 
</script> 
<form> 
<select name="countries" onchange="prodSearch(this.value)"> 
<option>Select a country:</option> ... 
<div id="searchResults"> 
</div> 

這是我的PHP:

<?php 
/* Get data from form */ 
$country = $_GET["country"]; 

/* Build query */ 
$result = "SELECT .... "; 

while($row = $modx->db->getRow($result)) { 
    echo "<pre>"; 
    print_r($row); 
    echo "</pre>"; 
} 

?> 

我到數據庫查詢作品完美,我可以在ps.php是返回結果Firebug的控制檯中看到。然而,我似乎無法得到它實際上填充結果searchResults div。我究竟做錯了什麼?

+1

你能'警報(xmlhttp.responseText)'?它是否提醒預期的結果? – Tchoupi 2012-08-08 19:39:40

+0

我在'document.getElementById ... responseText'之前放置了'alert(xmlhttp.responseText)',我根本沒有收到警報。 – Vecta 2012-08-08 19:49:08

+1

實際調用了'xmlhttp.onreadystatechange'嗎?你可以在這行之前提醒'xmlhttp.readystate':if(xmlhttp.readystate == 4 && xmlhttp.status == 200){'? – Tchoupi 2012-08-08 19:53:21

回答

3

readyState有資本S.更改爲if條件:

if(xmlhttp.readyState==4 && xmlhttp.status==200) { 
+0

OOF ...就是這樣。謝謝你的幫助! – Vecta 2012-08-08 20:03:38

+0

@Vecta不客氣:)我花了一段時間纔看到它。 – Tchoupi 2012-08-08 20:04:20