2014-08-27 103 views
0

我正在構建兩個相互依賴的下拉列表,其中第二個列表('sensor_list')的選項取決於在第一個列表(「node_list」)中選擇了哪個選項。爲此,我將一個偵聽器附加到'node_list'上,當選擇一個選項時,我發出一個ajax請求來加載'sensor_list'的數據。這兩個列表的所有數據都從同一個數據庫加載。如何從ajax請求返回JSON格式的數組?

在那個ajax請求我訪問數據庫的'傳感器'表,我得到'Sensor_ID'和'Sensor_name'我需要的傳感器。我現在想要的是將這些數據傳回給請求的'成功'功能。這是否自動完成?我是否需要將任何參數傳遞給函數?

此外,我需要返回的數據是JSON格式,供以後使用。這怎麼可能?

這裏是PHP代碼:

<?php 

$con = mysql_connect("localhost", "root", "") or die('connection not made'); 
$db = mysql_select_db('name_of_db', $con) or die('db not selected'); 

$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)"; 
$result = mysql_query($query, $con) or die('query not made'); 

$options = json_encode($result); 


?> 

在「node_selected」是我通過與請求的變量,它是我在第一列表中所選擇的節點的ID。

的JavaScript是:

if (node_selected!=0 & node_selected!=null){ 
       $.ajax({ 
        type: "POST", 
        url: "php/fetch_sensors.php", 
        data: node_selected, 
        success: function(options){ 
         ...//here I need the options to be in json format 
        } 
       }); 
      } 

「選項」是我想從請求返回的數據,他們將要爲「sensor_list」的選項。

非常感謝!

回答

0

可以使用mysql_fetch_assoc函數,該函數

嘗試改變PHP代碼如下:

<?php 

$con = mysql_connect("localhost", "root", "") or die('connection not made'); 
$db = mysql_select_db('name_of_db', $con) or die('db not selected'); 

$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)"; 
$result = mysql_query($query, $con) or die('query not made'); 

$returnArray = array(); 
while($row = mysql_fetch_assoc($result)) { 
    $returnArray[] = $row; 
} 

$options = json_encode($returnArray); 

?> 
0

變化

$options = json_encode($result); 

echo json_encode($result); 

並添加dataType:'json'到您的通話ajax

$.ajax({ 
    type: "POST", 
    url: "php/fetch_sensors.php", 
    data: node_selected, 
    dataType: 'json', 
    success: function(options){ 
     ...//here I need the options to be in json format 
    } 
}); 
+0

@Debflav你可以編輯答案而不是評論.. – 2014-08-27 14:13:14

+0

@Debflav我明白我只是說你可以編輯答案,如果它有一個語法錯誤。用戶會看到你的編輯,並感謝編輯:) – 2014-08-27 14:22:00

+0

我做到了,但它沒有奏效。另外,我提醒('hello');在成功功能裏面,但它從來沒有出現過。當我嘗試運行'fetch_sensors.php'分開時,只有一個空白頁。 – DimitrisChousiadas 2014-08-27 14:23:39

0

首先,stop using ext/mysql if you can

您實際上沒有從查詢中獲取結果。

while ($row = mysql_fetch_assoc($results)) { 
    $rows[] = $row; 
} 

然後你實際上必須發出數組到響應。

echo json_encode($rows); 

jQuery是非常聰明的檢測JSON和應該自動解析它,所以你可以使用options作爲一個對象。如果沒有自動運行,你可以做以下任一:

//php 
header("Content-type: application/json") 

//javascript 
data: node_selected, 
dataType: "json", 

// *or* 
success: function (options) { 
    options = JSON.parse(options); 
} 

最後,因爲這個要求是你真正應該使用GET代替POST的方法冪等檢索。