2013-05-03 50 views
-1

我發現很多關於這個主題的問題只有很少的投票,但我似乎無法得到任何迄今爲止的工作答案。我在Web服務器上創建了一個PHP頁面,將其轉換爲application/json,將mysqli查詢轉換爲數組,並使用json_encode對其進行編碼,使其成爲JSON對象。我現在正在嘗試使用javascript解碼JSON對象,但唯一能找到的解決方案是處理數組而不是對象。最終,我想解碼JSON並遍歷它,以便我可以將數據插入到客戶端上的Sqlite數據庫中。我很難在客戶端上得到任何結果,除非能夠對JSon進行字符串化,以便我能夠看到它已被檢索。我的代碼如下:使用Javascript解碼PHP編碼的JSON對象

Web服務器retrieveJSON.php頁面

<?php header('Content-Type: application/json'); 

$mysqli= new mysqli("host","user","password","database"); 

mysqli_select_db($mysqli,"database"); 

$query = "SELECT * FROM AppCustomers"; 
$result = mysqli_query($mysqli,$query) or die('Errant query: '.$query); 

$customers = array(); 
if(mysqli_num_rows($result)) { 
    while($customer = mysqli_fetch_assoc($result)) { 
    $customers[] = array('customer'=>$customer); 
    } 
} 

$json_array = array('customers'=>$customers,); 

echo json_encode($json_array); 

mysqli_close($mysqli); 
?> 

客戶端的JavaScript

<script> 
    $.ajax({ 
    url  : 'http://webserver/retrieveJSON.php', 
    dataType : 'json', 
    type  : 'get', 
    success : function(Result){ 
      //ResultAlert = JSON.stringify(Result); 
      //alert(ResultAlert); 
      } 
    }); 
</script> 

當我字符串化的結果我得到下面的JSON對象的長版:

{"customers":[{"customer":{"id":"1","customerName":"Customer Alpha","customerID":" custA","customerAddress":" Alpha Way","customerCity":" Alpha","customerState":" AL","customerZip":"91605"}},{"customer":{"id":"2","customerName":"Customer Beta","customerID":" CustB","customerAddress":" Beta Street","customerCity":" Beta","customerState":" BE","customerZip":"91605"}}]} 

我有一個數據庫和下面的插入功能已經設置。

function insertCustomer(customerName, customerID, customerAddress, customerCity, customerState, customerZip) { 
db.transaction(function (tx) { 
    tx.executeSql('INSERT INTO Customers (customerName, customerID, customerAddress, customerCity, customerState, customerZip) VALUES (?, ?, ?, ?, ?, ?)', [customerName, customerID, customerAddress, customerCity, customerState, customerZip],CountReturns); 
}); 

};

如何將對象轉回到數組中,以便我可以遍歷它並將每個字段插入到Sqlite數據庫中?換句話說,我用什麼替換// stringify部分?我希望這個問題不是太本地化,但我試圖闡明整個過程,以防其他人試圖做同樣的事情。該流程中的任何其他提示或建議也受到歡迎。謝謝。

感謝Quentin我能夠訪問數組並使用下面的代碼來代替stringify輸入字段到數據庫中;然而,由於某種原因,所有的輸入都是不確定的。

for (var i = 0, len = Result.customers.length; i < len; ++i) { 
    var customer = Result.customers[i]; 
    insertCustomer(customer.customerName, customer.customerID, customer.customerAddress, customer.customerCity, customer.customerState, customer.customerZip); 
    } 
+1

您正在尋找['JSON.parse'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)。 – 2013-05-03 16:32:13

回答

2
  1. 不要字符串化它
  2. 在JSON最外面的數據類型是一個對象(或,在PHP術語,關聯數組)。它有一個屬性customers其中包含一個數組。你可以用Result.customers得到它。