我在使用 JS 从后端(PHP)获取数据时遇到问题 - XMLHTTP 请求

问题描述 投票:0回答:1

我真的被这个问题困住了,把头撞在桌子上。 我通常尝试单独解决这些类型的问题,但截止日期已近,希望得到一些帮助。

这是后端代码,它正确显示数据 PHP 文件

<?php
include ("_inc_dbvars.php");
$idu = 2; // These variables i get from $_SESSION, for simplicity I made them static.
$idm = 2; //
$result_total=0;
$result_max=0; 
$zero_count = 0; // Count of answer values that are 0
$non_zero_count = 0; // Count of answer values that are not 0
$row_count = 0;
$result_total = 0;
$result_max = 0;
$score = 0;


try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT * from user_answer_values where user_id=:idu and module_id=:idm");
    $stmt->bindParam(':idu', $idu);
    $stmt->bindParam(':idm', $idm);
    $stmt->execute();

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $row_count++;

        if ($row['answer_value'] == 0) {
            $zero_count++;
        } else {
            $non_zero_count++;
            $result_total = $result_total + $row['answer_value'];
        }

    }

    $result_max = $row_count * 5;
    $score = round(($result_total / $result_max) * 100);
    $hdi = round(($result_total / $result_max)*200);
    $reliability = round(($non_zero_count / $row_count) * 100);

    
    $color_score = "#FFF";    
    $data = array(
        "Max" => htmlspecialchars($result_max, ENT_QUOTES, 'UTF-8'),
        "Score" => htmlspecialchars($result_total, ENT_QUOTES, 'UTF-8'),
        "ScorePercent" => htmlspecialchars($score, ENT_QUOTES, 'UTF-8'),
        "Reliability" => htmlspecialchars($reliability, ENT_QUOTES, 'UTF-8'),
        "HDI" => htmlspecialchars($hdi, ENT_QUOTES, 'UTF-8')
    );

    header('Content-Type: application/json');
    echo json_encode($data);

} catch(PDOException $e) {

    $data = array(
        "Error" => "Connection failed: " . $e->getMessage()
    );
    echo json_encode($data);
}
?>

数据:

{
  "Max": "295",
  "Score": "119",
  "ScorePercent": "40",
  "Reliability": "81",
  "HDI": "81"
}

这是JS请求

let hxttp = new XMLHttpRequest();
hxttp.onreadystatechange = function() {
  console.log(this.readyState);
    if (this.readyState == 4 && this.status == 200) {
        let data = JSON.parse(this.responseText);
        console.log(data);
    }
};
hxttp.open("GET", "../include/_inc_score.php", true);
hxttp.send();

"../include/_inc_score.php"
是正确的文件位置。 谢谢提前。

我有 7 个单独的模块,它们都需要访问它们的分数。 我使用 JS 单独且响应式地渲染它们。 似乎无法获取 JSON 数据...

编辑:控制台中的网络选项卡 https://imgur.com/a/HA94SZo

javascript php json xmlhttprequest
1个回答
0
投票

记住孩子们,仔细检查控制台,看看您是否在控制台的正确部分中查找。 我在错误部分,甚至没有看到数据正确显示。

© www.soinside.com 2019 - 2024. All rights reserved.