2015-08-26 125 views
0

我想運行一個php腳本,通過點擊一個按鈕來從數據庫中提取數據。我想使用Ajax,因此頁面不刷新。我測試過使用普通的post/submit與頁面刷新,它的工作原理,但我無法使用Ajax來顯示數據。這是我的代碼:使用ajax顯示數據與PHP和POST時出現問題

<form method="get" id="ghosts"> 
     <div id=rightc> 
       <h7>Select Hosts:</h7> 
    <br></br> 

     <select id="group" name="group" onchange='this.form.submit()'> 
      <?php 
     $link=mysql_connect($mysqlserver, $username, $password) or die ("Error connecting to mysql server: ".mysql_error()); 
     mysql_select_db($dbname, $link) or die ("Error selecting specified database on mysql server: ".mysql_error()); 
     $gquery=" SELECT groupname FROM groups"; 
     $gresult=mysql_query($gquery) or die ("Query to get data from firsttable failed: ".mysql_error()); 
     while ($grow=mysql_fetch_array($gresult)) { 
     $groupname=$grow["groupname"]; 
      echo "<option>$groupname</option>"; 
     } 
     ?> 
    </select> 
    <input type="hidden" name="ghosts" value="1" /> 
    <noscript> <input type="submit" name="ghosts" id="group" value="Choose Group" /></noscript> 

    </form> 
+1

表單的輸入字段在哪裏? –

+1

使用GET方法並使用POST獲取值'isset($ _ POST ['ahosts'])' – Saty

+1

大的線索。 **'$(「。result」)'不匹配任何內容** – Popnoodles

回答

4

如果您的search.php文件返回的HTML,並假設Ajax的工作原理(它看起來像它應該),你試圖把內容插入不元素存在。

$(".result").html(data); 

它需要存在於頁面上。添加這個地方。

<div class="result"></div> 

但是,你的PHP不返回的,因爲這種情況if(isset($_POST['ahosts']))其請求參數,是不是在形式和使用錯誤的請求方法的任何數據。

您使用GET($.get()),所以在PHP它需要讀取

if(isset($_GET['ahosts'])) 

並添加此表單內給予按鈕的名稱

<input type="hidden" name="ahosts" value="1" /> 
<!-- or --> 
<button type="submit" name="ahosts" /> 
0

我認爲你在這裏犯了一個錯誤:

if(isset($_POST['ahosts'])) 

Yo ü檢查isset() POST請求,但實際上您發送GET請求......

閱讀文檔https://api.jquery.com/jquery.get/

所以,如果你改變你的代碼:

if(isset($_GET['ahosts'])) 

這將返回true,那麼現在就有迴應

+0

非常感謝你們! - Popnoodles非常感謝您的建議爲我解決了這個問題 - 太棒了! :) – spyda46

+0

嗨,大家好,只是後續問題。我有一個類似於上面的形式,但這一個使用下拉菜單來選擇一個「組」我已經使用了與上述ajax相同的邏輯,頁面工作在某種意義上,我得到了預期的結果,但問題是頁面不刷新,我添加了上面的新代碼: – spyda46

+0

嗨,使用Ajax的主要原因是爲了防止刷新頁面 –