我正在尝试编写 AJAX 请求,但服务器的响应无效,因为这是一个错误。
回复:
<br /> <b>Warning</b>: parse_ini_file(config/config.ini): Failed to open stream: No such file or directory in <b>C:\xampp\htdocs\php\eindwerk\src\Promptopolis\Framework\Db.php</b> on line <b>9</b><br />
因此它无法解析 config.ini 文件,因此它也无法建立数据库连接。
但是,在我尝试 AJAX 请求之前,在页面本身上,我已经从数据库中获取了数据,这一切都是正确的,并且可以毫无问题地显示出来。所以配置文件在发送 AJAX 请求之前得到解析。
具体发送AJAX请求时,不知道为什么解析config.ini文件失败
我的数据库.php:
<?php
namespace Promptopolis\Framework;
abstract class Db {
private static $conn;
private static function getConfig(){
// get the config file
return parse_ini_file("config/config.ini");
}
public static function getInstance() {
if(self::$conn != null) {
// REUSE our connection
return self::$conn;
}
else {
// CREATE a new connection
// get the configuration for our connection from one central settings file
$config = self::getConfig();
$database = $config['database'];
$user = $config['user'];
$password = $config['password'];
$host = $config['host'];
self::$conn = new \PDO("mysql:host=$host;dbname=".$database, $user, $password);
return self::$conn;
}
}
}
我的剧本:
<script>
//add click event to voted button
const voted = document.querySelector('[name="voted"]');
//add eventlistener
voted.addEventListener('click', (e) => {
e.preventDefault();
//get user id
let user_id = <?php echo $id ?>;
//create formdata object
let formData = new FormData();
//append user id to formdata
formData.append('user_id', user_id);
fetch("ajax/votes.php", {
method: "POST",
body: formData
})
.then(function(response){
return response.json();
})
.then(function(json){
//update counter
voting.innerHTML = json.votes;
});
});
</script>
My votes.php:
<?php
require_once('../vendor/autoload.php');
if (!empty($_POST)) {
$user_id = $_POST['user_id'];
$user = new \Promptopolis\Framework\User();
$moderator = new \Promptopolis\Framework\Moderator();
$moderator->updateVotes($user_id);
$user->checkAdmin($user_id);
$votes = $user->getVotes($user_id);
$result = [
"status" => "success",
"message" => "Vote was saved",
"votes" => $votes
];
echo json_encode($result);
}
答案
我不得不把
parse_ini_file("config/config.ini")
改成parse_ini_file($_SERVER['DOCUMENT_ROOT']."/config/config.ini")
这样就可以从 ajax 文件夹中解析 ini 文件。