在javascript中读取PHP关联数组值

时间:2017-12-14 07:41:14

标签: php jquery ajax

我尝试从数据库值生成简单的图表。我使用AJAX从数据库中获取值并将其返回给javascript。我想用canvas生成这个值的图表,但我不知道如何在javascript中读取关联PHP数组。

@EDIT

AJAX请求:

$.post({
    type: "POST",
    url: "execute.php",
    data: {producer: producer, before: before, after: after, name: name},
    dateType: 'json',
    cache: false,
}).done(function(data) { 
    $("#xdebug").html(data);
});

PHP结果如下所示:

$params = array();

foreach(array_unique($dates) as $date) { 
    $params[] = array("date" => $date, "sold" => sumOrders($date, $dbh), "scale" => sumOrders($date, $dbh) * 10);
}

echo json_encode($params);

我在javascript中收到一个这个数组

[{
    "date": "2017-12-01",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-02",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-03",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-04",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-05",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-06",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-07",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-08",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-09",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-10",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-11",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-12",
    "sold": "0",
    "scale": 0
}, {
    "date": "2017-12-13",
    "sold": "0",
    "scale": 0
}]

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

你从PHP获得一个JS数组,它就像一个普通的JS数组

$.post({
    type: "POST",
    url: "execute.php",
    data: {producer: producer, before: before, after: after, name: name},
    dataType: 'json',
    cache: false,
}).done(function(data) { 
    // do something with your array, as in snippet after
});

编辑:您的属性中的拼写错误dateType => dataType

执行循环,但没有人知道除了你该如何处理它!

 var data = [{"date":"2017-12-01","sold":"0","scale":0},{"date":"2017-12-02","sold":"0","scale":0},{"date":"2017-12-03","sold":"0","scale":0},{"date":"2017-12-04","sold":"0","scale":0},{"date":"2017-12-05","sold":"0","scale":0},{"date":"2017-12-06","sold":"0","scale":0},{"date":"2017-12-07","sold":"0","scale":0},{"date":"2017-12-08","sold":"0","scale":0},{"date":"2017-12-09","sold":"0","scale":0},{"date":"2017-12-10","sold":"0","scale":0},{"date":"2017-12-11","sold":"0","scale":0},{"date":"2017-12-12","sold":"0","scale":0},{"date":"2017-12-13","sold":"0","scale":0}];
    
    
    for(var i in data){
      console.log(data[i].date);
      console.log(data[i].sold);
      console.log(data[i].scale);
    }

答案 1 :(得分:2)

首先,你的ajax代码中有一个拼写错误:

ETags

现在cache中的响应将是一个json对象,您可以轻松使用它:

$.post({
    type: "POST",
    url: "execute.php",
    data: {producer: producer, before: before, after: after, name: name},
    dataType: 'json', //dataType not dateType
    cache: false,
}).done(function(data) { 
    $("#xdebug").html(data);
});