Php echo json_encode数组进入javascript数组

时间:2014-02-17 04:46:05

标签: javascript php

我正在尝试将帖子发送到php脚本,该脚本将使用此收集数据库中的所有帐户信息...

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);
?>

我需要回显的json_encode在返回数据上输入javascript。如何将数据转换为数组?

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

数据设置为“{”名称“:”商家名称“,”CRN“:null,”ID“:”17“,”类型“:”用户“,”收入“:null,”行业“:”软件&amp; Internet“,”“Description”:null,“Employees”:null,“Billing”:“An Address”,“Shipping”:“An Address”,“Detail75”:{“Label”:“Phone”,“Value”: “电话号码”},“详情76”:{“标签”:“电子邮件”,“价值”:“电子邮件地址”}}“返回时”

2 个答案:

答案 0 :(得分:1)

从您的php传入json_encode()'ed数据,例如:

...
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);

在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
});

答案 1 :(得分:0)

首先将数据类型设置为JSON

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

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