JS - 在网络服务器上获取 .php 文件给出 404

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

我正在尝试将一些数据从 MySQL 数据库加载到 HTML 网站中。我目前的方法是一个 PHP 脚本,它将数据库数据作为 JSON 返回,然后是一个 JS 脚本,该脚本使用该数据创建 HTML 元素。

所有文件都托管在网络服务器上,目前所有文件都在同一目录中。运行时我收到以下错误:

GET http://www.<website>.com/fetch_data.php 404 (Not Found)

这是我的 PHP 脚本:

<?php
// Create a connection to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check if the connection was successful
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Construct the SQL query to retrieve player data
$sql = "SELECT * FROM players";

// Execute the SQL query and store the result
$result = $conn->query($sql);

// Check if any rows were returned
if ($result->num_rows > 0) {
  $players = array();
  // Loop through each row and store the player data in an array
  while ($row = $result->fetch_assoc()) {
    $player = array(
      "name" => $row["name"],
      "description" => $row["description"],
      "hcp" => $row["hcp"],
      "image" => $row["image"]
    );
    array_push($players, $player);
  }
  // Encode the array as JSON and return it
  header('Content-Type: application/json');
  echo json_encode($players);
} else {
  echo "No players found";
}

// Close the database connection
$conn->close();
?>

这是我在 HTML 中包含的 JS 脚本:

// Container reference
const gridContainer = document.querySelector(".grid-container");

// Fetch the data from the database
const xhr = new XMLHttpRequest();
xhr.open("GET", "./fetch_data.php");
xhr.onload = function() {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    // Loop through the data and create a grid item for each player
    data.forEach(player => {
      const gridItem = document.createElement("div");
      gridItem.classList.add("grid-item");
      gridItem.innerHTML = `
        <div class="top-wrapper">
          <div class="img-wrapper">
            <img src="pics/${player.image}" alt="${player.name}">
          </div>
          <div class="info-wrapper">
            <h2>${player.name}</h2>
            <p>${player.description}</p>
          </div>
        </div>
        <div class="stats-wrapper">
          <div class="stats-item">
            <h3>HCP</h3>
            <p>#${player.hcp}</p>
          </div>
        </div>
        <div class="input-wrapper">
          <input type="text" placeholder="???"/>
          <button class="input-btn"><i class="fa-solid fa-paper-plane"></i></button>
        </div>
      `;
      gridContainer.appendChild(gridItem);
    });
  } else {
    console.error(xhr.statusText);
  }
};
xhr.send();

感谢任何帮助——也请随时对我的方法提出意见。

javascript php mysql get xmlhttprequest
© www.soinside.com 2019 - 2024. All rights reserved.