我现在正在从事这个项目,但是我遇到了这个小问题。如何使用带有Vue.js的PHP OOP获取记录?似乎没有其他方法可以在类函数中的url中传递变量。我正在使用Axios.js发送AJAX请求。如何改善这一点并能够从axios.js提取数据?
Index.php
<div id="admin">
<div class="col-md-12">
<table class='table table-bordered table-striped'>
<thead>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>User Type</th>
<th>Delete</th>
</thead>
<tbody>
<?php
require_once'function.php';
$show_users=new DB_con();
$sql1=$show_users->show_users();
$cnt=1;
while($row=mysqli_fetch_array($sql1))
{
?>
<tr v-for="show_user in show_users">
<td><?php echo htmlentities($cnt);?></td>
<td><?php echo htmlentities($row['fname']);?> {{ show_user.fname }}</td>
<td><?php echo htmlentities($row['lname']);?>{{ show_user.lname }}</td>
<td><?php echo htmlentities($row['username']);?>{{ show_user.username }}</td>
<td><?php echo htmlentities($row['user_type']);?>{{ show_user.usertype }}</td>
<td><a href="index.php?del=<?php echo htmlentities($row['id']);?>"><button class="btn btn-danger btn-xs" onClick="return confirm('Do you really want to delete');"><span class="glyphicon glyphicon-trash"></span>Delete</button></a></td>
</tr>
<?php
$cnt++;
} ?>
</tbody>
</table>
</div>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script src="js/app.js"></script>
app.js
var app = new Vue({
el: '#admin',
data:{
show_users: []
},
mounted: function(){
this.getAllUsers();
},
methods:{
getAllUsers: function(){
axios.get("function.php")
.then(function(response){
//console.log(response);
app.show_users = response.data.show_users;
});
}
}
});
function.php
<?php
session_start();
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'e4');
class DB_con
{
function __construct()
{
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
$this->dbh=$con;
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function show_users()
{
$reg=mysqli_query($this->dbh,"SELECT id, fname, lname, username, remark, user_type FROM e4_users as a join e4_user_type as b on b.userId=a.userId WHERE a.userId='2' AND remark='1' ");
return $reg;
}
}
?>
您的function.php
现在负责启动会话,定义MySQL连接变量,还拥有一个负责连接MySQL的类。
您不想这样做,而是遵循称为关注点分离(click here)的原则。
[以非ajax的方式,就像现在在index.php
中一样,您要包含function.php
文件,您正在实例化您的类并调用该函数以从数据库返回结果,然后循环遍历它们。
如果您希望axios ajax调用获得这些结果,则需要调用一个实际提供这些结果的文件。
您可以做的是制作一个新文件,假设为show_users.php
,然后放入类似这样的内容:
<?php
require_once'function.php';
$show_users=new DB_con();
$sql1=$show_users->show_users();
$array = mysqli_fetch_assoc($sql1);
header('Content-type: application/json');
echo json_encode($array);
?>
然后,确保将axios呼叫从axios.get("function.php")
更改为axios.get("show_users.php")
。
尽管我不得不说,用PHP手动完成所有这些工作是很多不必要的工作。通过选择一个可以为您完成许多工作的框架,您会更加轻松,安全。 Laravel