2014-02-17 28 views
0

我想發個帖子的PHP腳本,它會收集來自使用該數據庫中的所有帳戶信息...PHP的echo json_encode數組轉換成JavaScript數組

var e = document.getElementById("lstAccounts"); 
var accountID = e.options[e.selectedIndex].value; 
alert("Account ID:"+accountID); 
$.post("php/getAccount.php", {ID: accountID}, function(data) 
{ 
    var accountInfo = data; 
}); 

這個帖子這個...

<?php 
$id = $_POST['ID']; 
include('database_api.php'); 
$db = new DatabaseControl; 
$db->open_connection(); 
$result = $db->db_query("SELECT * FROM tblAccount WHERE ID=$id"); 
$account_info = array(); 
//Get Basic Information 
while($row = mysqli_fetch_array($result)) 
{ 
    $account_info['Name'] = $row['Name']; 
    $account_info['CRN'] = $row['CRN']; 
    $account_info['ID'] = $row['ID']; 
    $account_info['Type'] = $row['Type']; 
    $account_info['Revenue'] = $row['Revenue']; 
    $account_info['Industry'] = $row['Industry']; 
    $account_info['Description'] = $row['Description']; 
    $account_info['Employees'] = $row['NoOfEmployees']; 
    $account_info['Billing'] = $row['BillingAddress']; 
    $account_info['Shipping'] = $row['ShippingAddress']; 
} 
//Get Details 
$result = $db->db_query("SELECT tblDetails.ID, tblDetails.Label, tblDetails.Value FROM tblAccountDetails 
          INNER JOIN tblDetails ON tblDetails.ID = tblAccountDetails.DetailID 
          WHERE AccountID=$id"); 
//Get Basic Information 
while($row = mysqli_fetch_array($result)) 
{ 
    $account_info['Detail'.$row['ID']]['Label'] = $row['Label']; 
    $account_info['Detail'.$row['ID']]['Value'] = $row['Value']; 
} 
//Get Contact Information 

//Get Invoices 

//Get Payments 

//Get Notes 

//Get To-Do 

//Events 

//Send back to javascript 
echo json_encode($account_info); 
?> 

我需要echo的json_encode在返回數據上輸入javascript。如何將數據存入數組?

$.post("php/getAccount.php", {ID: accountID}, function(data) 
{ 
    //In here how do I decode data into a javascript array 
}); 

的數據被設置爲 「{」 名稱 「:」 一個企業的名字」, 「CRN」:空, 「ID」: 「17」, 「類型」: 「用戶」, 「收入」: 「行業」:「軟件&互聯網」,「說明」:空,「員工」:空,「計費」:「地址」,「發貨」:「地址」,「詳細信息75」:{「標籤」 :「Phone」,「Value」:「電話號碼」},「Detail76」:{「Label」:「Email」,「Value」:「電子郵件地址」}}「返回

回答

1

傳入json_encode() '從您的PHP編輯數據,如:

... 
while($row = mysqli_fetch_array($result)) 
{ 
    $account_info['Detail'.$row['ID']]['Label'] = $row['Label']; 
    $account_info['Detail'.$row['ID']]['Value'] = $row['Value']; 
} 
echo json_encode($account_info); 

in js部分:

$.post("php/getAccount.php", {ID: accountID}, function(data) { 
    //parse the json response 
    var response = jQuery.parseJSON(data); 
    console.log(response); //you can use $.each to iterate the data 
}); 
+0

酷非常感謝,我會嘗試這種 –

+0

謝謝你這工作了魅力:d:d –

+0

@TomHanson歡迎您..順便說一句,你可以標記它作爲接受答案,如果它爲你工作:) –

0

第一盤的數據類型爲JSON

$.post("php/getAccount.php", {ID: accountID}, function(data) 
{ 

    // Confirm Response 
    console.log(data); 
    $.each(data, function(i, e){ 
     console.log(e); 
    }); 
}, 'json');