使用PHP返回数组的Javascript

时间:2017-01-13 00:24:06

标签: javascript php html arrays

基本上,我正在尝试将请求发送到查询我的数据库的单独.php文件。尝试将数组作为变量类型数组返回时,会发生此问题。我需要这个,因为我想在发送到HTML时将它发送到另一个PHP。在第二个PHP文件中,我想使用for-each-loop-statement来创建一些代码,但这只需要数组而不是字符串。我尝试过几个方面,包括使用JSON来尝试解决这个问题,但是在返回时,数组会变成一个字符串。任何帮助,将不胜感激。最相关的代码包含在下面:

的javascript:

function getEvents(){ //gets the events from the database
  var req = new XMLHttpRequest();
  var att = 1;            //Just a filler because somehow this seems needed
  var link = "IekjeConnector.php";

  dataType:"json";
  req.onreadystatechange = function() {
    if(req.readyState === 4 && req.status === 200)
    {
      addEvents(JSON.parse(this.responseText)); //This should be a normal array
    }
  }
  req.open("GET", link + "?att=" + att, true);
  req.send();
}

function addEvents(events = ""){ 
  var req = new XMLHttpRequest();
  var link = "IekjeHome.php"; //sends to the next php

  req.onreadystatechange = function() {
    if(req.readyState === 4 && req.status === 200)
    { document.getElementById("event").innerHTML = this.responseText; }
  }

  req.open("GET", link + "?events=" + events, true); //events has the right value
  req.send();
}

PHP:

if (filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING)) {
  $events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
  $length = count($events);
  print_r(gettype($events));

  foreach($events as $event)
  { echo $events[$count] . $events[$count+2]; }
}

foreach返回一个错误,即$ events是一个字符串,gettype()也是如此。 我尝试改变addEvents和php代码接收数组的方式,但我可能做错了尝试。

2 个答案:

答案 0 :(得分:0)

我相信你所寻找的是JSON.parse(this.responseText)

答案 1 :(得分:0)

我认为您需要将字符串更改为数组,例如使用explode。

$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$events = explode(",",$events);

而不是“,”,只需放置事件的分隔符。