douping4436 2017-12-23 03:22
浏览 61

PHP多维数组到JavaScript

I want to print the data of a PHP array in a Javascript function... The problem is, it isn't working. This is how the datas get compounded in PHP:

$daten = array();
$anzahl = array();
$leads = array();
if ($result = $this->databaseConnection->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $daten[] = $row["Datum"];
        $anzahl[] = $row["Anzahl"];
    }
    $this->logger->lwrite('Leads: '. $leads);
    $leads[] = array(array("daten" => $daten), array("anzahl" => $anzahl));
    return json_encode($leads);
} 

This is what the JavaScript POST request:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }
xhttp.open("POST", "/requestLeadClicksController.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(jQuery('#formToRequestLeadClicks').serialize());

This is what I get on console.log(this.responseText);:

[[{"daten":["2017-12-21","2017-12-22","2017-12-23"]},{"anzahl":["1","2","1"]}]] 

And either this.responseText.daten, this.responseText[0], this.responseText[0].daten or this.responseText[daten] is working to print only the data array. What I want to get is only this:

"2017-12-21","2017-12-22","2017-12-23"

Same goes for the anzahl array. I also want to have only this:

"1","2","1"

I would appreciate any kind of help! Kind regards!

  • 写回答

2条回答 默认 最新

  • douchun1900 2017-12-23 03:34
    关注

    You have an array containing an array of objects that contain arrays of strings. To get down to the innermost arrays of strings, you need two array indexes followed by an object property.

    datenArray = responseText[0][0].daten,
    anzahlArray = responseText[0][1].anzahl;
    

    let responseText = [[{"daten":["2017-12-21","2017-12-22","2017-12-23"]},{"anzahl":["1","2","1"]}]],
        datenArray = responseText[0][0].daten,
        anzahlArray = responseText[0][1].anzahl;
    
    console.log( datenArray );
    console.log( anzahlArray );

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探