简体   繁体   English

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

[英]Why does the XHR succeed and show in chromeDevTools but is undefined and cant be parsed by JSON.parse()

here's the script: 这是脚本:

  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);
})
}

What is returned from "getRequests.php" is markup in JSON. 从“ getRequests.php”返回的是JSON中的标记。 Just for Reference, I'll post the backend code so you can look up what is put into the response. 仅供参考,我将发布后端代码,以便您可以查找响应中的内容。 "$result" is what is returned at the end of the php. “ $ 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("dmy",strtotime($row["anfang"]))."</td><td>" .date("dmy",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); } } ?> 

In the chromeDevTools, the response is displayed correctly as HTML elements ("" and the like). 在chromeDevTools中,响应正确显示为HTML元素(“”等)。 However, when I try to output the results via console.log I get "undefined". 但是,当我尝试通过console.log输出结果时,得到“未定义”。 When I try to parse it with "JSON.parse()" it gives me a syntax error saying that there was an "unexepected expression at line 1 column 1" of the data. 当我尝试使用“ JSON.parse()”解析它时,它给了我一个语法错误,说数据中存在“第1行第1列的意外表达式”。

I don't understand this, especially since I used the very same script code before in other parts of the site. 我不明白这一点,尤其是因为我之前在网站的其他部分使用了完全相同的脚本代码。 There, this problem never appeared. 在那里,这个问题从未出现过。

I think you get undefined for data in the .then((data) => { data = JSON.parse(data) block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed). 我觉得你得到了一个未定义的data.then((data) => { data = JSON.parse(data)块,因为这个“然后”连接到呼叫getLoggedUser,不GetRequest的。因此,它接收不同的响应(并且也可能在getRequests完成之前执行)。

So you need to do two things 所以你需要做两件事

1) Attach your callback to the correct AJAX call 1)将您的回调附加到正确的AJAX调用

2) stop trying to use JSON to try and wrap around HTML. 2)停止尝试使用JSON尝试环绕HTML。 What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML. 您传递给json_encode()的不是JSON,也没有必要-只需将HTML作为字符串返回并直接附加到HTML即可。

JS: 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: PHP:

Simply replace 只需更换

echo json_encode($result);

with

echo $result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM