我想在Javascript函数中打印PHP数组的数据......问题是,它无法正常工作。这就是数据在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);
}
这是JavaScript POST请求:
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());
这就是我在console.log(this.responseText);
上得到的:
[[{"daten":["2017-12-21","2017-12-22","2017-12-23"]},{"anzahl":["1","2","1"]}]]
并且this.responseText.daten
,this.responseText[0]
,this.responseText[0].daten
或this.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;
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 );
如果你想自动返回,你可以使用递归迭代器(我使用jQuery来做)。这个迭代器只有在返回的键是关联的(不是数字的)时才有效,尽管可以改变它来做你想做的任何事情:
var arr = [[{"daten":["2017-12-21","2017-12-22","2017-12-23"]},{"anzahl":["1","2","1"]}]];
var arrfin = {};
function recurse(array)
{
$.each(array,function(k,v){
if(typeof v === "object") {
if(typeof k !== "number")
arrfin[k] = v;
else
recurse(v);
}
});
}
recurse(arr);
console.log(arrfin.daten);
console.log(arrfin.anzahl);
这将在控制台中给出:
["2017-12-21", "2017-12-22", "2017-12-23"]
["1", "2", "1"]