2012-05-28 33 views
0

我正在研究這個小應用程序,我遇到了一個小問題。php,ajax,html select元素

我有3個下拉菜單(namedatepath)。 用戶要選擇一個名稱,那麼該用戶的日期應顯示在日期下拉菜單中。 然後用戶選擇一個日期,然後路徑名將顯示在相應的下拉菜單中。 用戶然後選擇一個路徑,其他的東西發生在這一點上並不重要。我在服務器端(我很舒服)使用PHP和javascript/ajax我基本上沒有經驗。據我的理解,我需要使用AJAX技術,以便整個頁面不必重新加載,而不需要那些下拉菜單。

我有名稱下拉菜單生成,但我很難搞清楚如何做日期和路徑的。

現在我有一些簡單的getter(其中一個在下面),我認爲這可以幫助我完成我想要完成的任務(糾正我,如果這些不會幫助)。我也一直在閱讀一本關於AJAX和研究互聯網的書,但還沒有弄清楚其他的東西。任何幫助表示讚賞。

function getName(){<br/> 
    var nameSelect = document.getElementById("names");<br/> 
    var selectedName = nameSelect.options[nameSelect.selectedIndex].text;<br/> 
    return selectedName;<br/> 
} 
+0

你是什麼意思「日期」和「路徑」;格式是什麼? – 2012-05-28 18:07:20

回答

4

使用jQuery,它會幫助你忘記瀏覽器,並專注於編碼本身。

假設這是你的HTML和Javascript

<html> 
<head> 
    <title>Dropdowns</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
     // Detect if a change to the name dropdown is made 
     $("#name").change(function() { 

     // Setup the AJAX call (this is a call which expects JSON as response) 
     $.ajax({ 
      url: "http://example.com/api.php", 
      type: "json",       
      // Specify the GET parameter "name" with the value from the name dropdown 
      data: { 
       name: $("#name").val() 
      }, 

      // If AJAX was successfull add the regarding values to the date dropdown 
      success: function() {    
       // The response from PHP contains an array encoded in JSON. 
       // This means, we have to loop trough the results 
       $.each(data.directors, function() { 
        $("#date").append(
         // This actually appends the value on the date dropdown 
         $("<option></option>").val(this.value).html(this.label) 
        ) 
       }); 
      } 
     }); 

     // Detect if a change to the date dropdown is made 
     $("#date").change(function() { 

     // Setup the AJAX call (this is a call which expects JSON as response) 
     $.ajax({ 
      url: "http://example.com/api.php", 
      type: "json", 
      // Specify the GET parameter "date" with the value from the date dropdown 
      data: { 
       date: $("#date").val() 
      }, 

      // If AJAX was successfull add the regarding values to the path dropdown 
      success: function() { 

       // The response from PHP contains an array encoded in JSON. This means, we have to loop trough the results 
       $.each(data.directors, function() { 
        $("#path").append(
         // This actually appends the value on the path dropdown 
         $("<option></option>").val(this.value).html(this.label); 
        ) 
       }); 
      } 
    }); 
    </script> 
</head> 

<body> 
    <form name="someform"> 
     <select name="name" id="name"> 
      <option value="1">John Smith</option> 
      <option value="2">Peter Johnson</option> 
     </select> 

     <select name="date" id="data"> 
      <option value=""></option> 
     </select> 

     <select name="path" id="data"> 
      <option value=""></option> 
     </select> 
    </form> 
</body> 
</html> 

你需要一個PHP文件,該文件輸出類似下面的數據:

<?php 
if($_GET['name'] != "" && isset($_GET['name'])) { 
    // Now you'd need some logic to generate an array, containing the information for this name 
    // We'll just create one manually now 

    $dates = array(); 

    $dates[]['value'] = "349876973"; 
    $dates[]['label'] = "Date description 1"; 
    $dates[]['value'] = "783693876"; 
    $dates[]['label'] = "Date description 2"; 

    echo json_encode($dates); 
} elseif($_GET['date'] != "" && isset($_GET['date'])) { 
    // Now you'd need some logic to generate an array, containing the information for this date 
    // We'll just create one manually now 

    $paths = array(); 

    $dates[]['value'] = "path value 1"; 
    $dates[]['label'] = "Path description 1"; 
    $dates[]['value'] = "path value 2"; 
    $dates[]['label'] = "Path description 2"; 

    echo json_encode($paths); 
} 

我無法測試它,但希望它給你一個關於AJAX和jQuery的想法。另請參閱jQuery Documentations和API參考,其中介紹了可用的方法和選項。

更新:您不必將值和標籤用作數組鍵名稱。但是,如果你願意,你可以創建一個看起來像這樣的查詢(這是一個PDO例子,你可能想進入PDO,因爲它爲你節省了轉義輸入的麻煩,並且使重複查詢更容易)。這將需要PHP的PDO functions,如果您位於託管服務器上,可能已經安裝了該服務。

包括/ db.include.php

<?php 
class example { 
    // Create database connection 
    public function __construct() { 
     $this->db = new PDO("pgsql:host=localhost;dbname=exampledb;", "user", "password"); 
     if(!$this->db) { 
      die("Connection failed!"); 
     } 
    } 

    // Get dates 
    public function getDates($name) { 
     $sql = "SELECT 
        date AS value, datedescription AS label 
       FROM 
        some_table 
       WHERE 
        name = ?"; 

     $stmt = $this->db->prepare($sql); 

     $stmt->bindParam(1, $name); 

     if(!$stmt->execute()) { 
      // Only for debugging, wouldn't use this on production 
      var_dump($stmt->errorInfo()); 
     } 

     $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 

     return $result; 
    } 

    // Get paths 
    public function getPaths($date) { 
     $sql = "SELECT 
        path AS value, pathdescription AS label 
       FROM 
        another_table 
       WHERE 
        date = ?"; 

     $stmt = $this->db->prepare($sql); 

     $stmt->bindParam(1, $date); 

     if(!$stmt->execute()) { 
      // Only for debugging, wouldn't use this on production 
      var_dump($stmt->errorInfo()); 
     } 

     $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 

     return $result; 
    } 

    // Close database connection 
    public function __destruct() { 
     @$this->db->close(); 
    } 
} 

?> 

而在你api.php你會去這樣

<?php 
include 'includes/db.include.php'; 

$example = new example; 

if(isset($_GET['name'])) { 
    echo json_encode($example->getDates($_GET['name'])); 
} elseif(isset($_GET['date'])) { 
    echo json_encode($example->getPaths()); 
} 

但正如我說的,你也可能會更改jQuery代碼,所以你的專欄不必被命名爲價值和標籤。假設你是表格中的日期被稱爲「日期」和「日期描述」,你只需使用這個代碼

$.each(data.directors, function() { 
    $("#date").append(
     // This actually appends the value on the date dropdown 
     $("<option></option>").val(this.date).html(this.datedescription) 
    ) 
}) 
+0

所以在上面的PHP腳本中,我需要連接(並關閉我的數據庫連接)。但是,我不確定如何使用postgres/php函數設置值和標籤。現在我正在嘗試使用以下來填充日期數組:$ userIdQuery =「從用戶中選擇id WHERE $ _GET [\'name \'] = username」; $ userId = pg_query($ db,$ userIdQuery); $ datesQuery =「從date WHERE $ userId [0] = dates.user_id」中選擇date_ridden; $ dates = pg_query($ db,$ datesQuery); echo json_encode($ dates); – lorenzo

+0

已更新的答案。 – Ahatius

+0

您應該將PDO的實例傳遞給對象,而不是讓對象創建它。 – Corbin