我正在简单地对数据库进行php查询,并且它以奇怪的对象响应,我找不到我在这里要求的内容。我知道如何在js中编码,但我是PHP的新手。
以下是代码:
的index.php
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function spytajBazy(request)
{
var wynik = $.ajax({
type: "post",
url: "ajax_requests.php",
data: {request: request},
success: function (result) {
return result;
}
});
var array = $.map(wynik, function(value, index) {
return [value];
});
return array;
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<title>Admin check</title>
<meta charset="UTF-8">
</head>
<body>
<script type='text/javascript'>
var wynik = spytajBazy("sprawdz_ile_grup");
var array = jQuery.makeArray(wynik);
console.log(wynik);
</script>
的functions.php
<?php
class Functions
{
private $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function sprawdz_ile_grup()
{
$query = "SELECT * FROM `groups`";
$result = $this->db->dataQuery($query);
return $result->fetchAll();
}
public function insert_something()
{
$query = "INSERT INTO `myDB`.`groups` (`id` ,`nazwa` ,`data_utworzenia`)VALUES ('5', 'randomsecond', '2016-05-18');";
$result = $this->db->dataQuery($query);
return $true;
}
}
database.php中
<?php
class Database
{
private $conn = null;
public function __construct()
{
try {
$username = "usrnm";
$password = "pass";
$servername = "server";
$dbname = "dbname";
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
trigger_error("Error: " . $e->getMessage());
}
}
public function dataQuery($query, $params = array())
{
try {
$stmt = $this->conn->prepare($query);
$stmt->execute($params);
return $stmt;
} catch (PDOException $e) {
trigger_error("Error: " . $e->getMessage());
};
}
}
ajax_requests.php
<?php
if (!empty($_POST)) {
$method = $_POST['request'];
include 'Database.php';
include 'Functions.php';
$db = new Database();
$functions = new Functions($db);
if (method_exists($functions, $method)) {
$data = $functions->$method();
header('Content-Type: application/json');
echo json_encode($data);
}
}
?>
答案 0 :(得分:0)
你的PHP代码可能不会像这样返回javascript函数。我认为错误在你的javascript代码中。
var wynik = $.ajax({ //...
为什么要在那里设置wynik变量?我认为你看到的控制台日志是$ .ajax函数。我敢打赌如果你改变这一行就可以了:
$.ajax({ //...