为什么XHR成功并显示在chromeDevTools中,但未定义并且无法通过JSON.parse()解析

时间:2018-11-08 09:20:33

标签: javascript php jquery json ajax

这是脚本:

  function getReq(){
 $.post('../include/getLoggedUser.php', {
  //nothing to transmit
}).then((loggedUser) => {
    $.post("../include/getRequests.php", {
    ID:loggedUser
  })
}).then((data) => {
  data = JSON.parse(data)
  console.log("data for table is", data)
  $("#requestTable").html(data);
})
}

“ getRequests.php”返回的是JSON中的标记。 仅供参考,我将发布后端代码,以便您可以查找响应中的内容。 “ $ result”是php末尾返回的内容。

<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
  if(isset($_POST["ID"])){
    try{
      $connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
      'verwalter','N7pY1OTl2gaBbc51');
    }catch(PDOException $e){
      echo $e->getMessage();
    }
    session_start();
    
    $userRole = $connection->query("
      SELECT name
      FROM rolle
      WHERE id = (
        SELECT rolle
        FROM benutzer_rollen
        WHERE benutzer='".$_POST["ID"]."'
      )
    ")->fetchAll()[0][0];
    if($userRole == "admin"){

      
      $result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
      </td><td>Aktionen</td></tr></thead><tbody>";

      $allReservation = $connection->query("
        SELECT id, anfang, ende, benutzer, arbeitsplatz
        FROM reservierung
        WHERE status='angefragt'
      ")->fetchAll();
      foreach($allReservation as $row){
        $user = $connection->query("
          SELECT name, vorname
          FROM benutzer
          WHERE id='".$row["benutzer"]."'
        ")->fetchAll()[0];
        $position = $connection->query("
          SELECT raum, nummer
          FROM arbeitsplatz
          WHERE ID = '".$row["arbeitsplatz"]."'
        ")->fetchAll()[0];
        $raumbild = $connection->query("
          SELECT bild
          FROM raum
          WHERE name ='".$position["raum"]."'
        ")->fetchAll()[0][0];


        $result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
        .date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
        .$user["vorname"]."</td><td><a>".$position["raum"]."/"
        .$position["nummer"]."<div><img class=\"hoverImage\"src=\"".$raumbild.
        "\" /></div></a></td><td><div class=\"form-inline form-horizontal\">
        <select id=\"statusDrop".$row["id"]."\" class=\"form-control\">
        <option>genehmigen</option><option>ablehnen</option></select>
        <button class='btn btn-default' onclick=\"submitStatus(".$row["id"].
        ");\">Ok</button></div></td></tr>";
      }
      $result .= "</tbody></table>";
      echo json_encode($result);
    }
  }


?>

在chromeDevTools中,响应正确显示为HTML元素(“”等)。但是,当我尝试通过console.log输出结果时,得到“未定义”。当我尝试使用“ JSON.parse()”解析它时,它给了我一个语法错误,表明数据中存在“第1行第1列的意外表达式”。

我不明白这一点,尤其是因为我之前在网站的其他部分使用了完全相同的脚本代码。在那里,这个问题从未出现过。

1 个答案:

答案 0 :(得分:0)

我认为您在data块中没有为.then((data) => { data = JSON.parse(data)定义,因为此“ then”附加到对getLoggedUser的调用上,而不是对getRequests的调用上。因此它收到一个不同的响应(也可能在getRequests完成之前执行)。

所以您需要做两件事

1)将回调附加到正确的AJAX调用

2)停止尝试使用JSON尝试环绕HTML。您传递给json_encode()的不是JSON,也没有必要-只需将HTML作为字符串返回并将其直接附加到HTML。

JS:

function getReq(){
  $.post('../include/getLoggedUser.php', {
    //nothing to transmit
  }).then((loggedUser) => {
    $.post("../include/getRequests.php", {
      ID:loggedUser
    }).then((data) => {
        console.log("data for table is", data)
        $("#requestTable").html(data);
    })
  })
}

PHP:

只需替换

echo json_encode($result);

使用

echo $result;