在php中使用ajax获取数据
我的数据库中有两个表,第一个是id表,另一个是文本表 我可以这样从数据库中获取数据 这是index.php文件在php中使用ajax获取数据,php,ajax,Php,Ajax,我的数据库中有两个表,第一个是id表,另一个是文本表 我可以这样从数据库中获取数据 这是index.php文件 <?php include "config.php"?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/java
<?php include "config.php"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<ul>
<?php
$result = $db->query("select * from veri ORDER BY id DESC ");
while ($row = $result->fetch_object()) {
echo '<li id="'.$row->id.'">'.$row->text.'</li>';
}
?>
</ul>
</body>
</html>
这个ajax.php文件
<?php
require "config.php";
if ($_POST) {
$lastid = $_POST["lastid"];
if (!$lastid) {
$array["error"] = "something is wrong";
} else {
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows()) {
while ($row = $query->fetch_object()) {
$array["data"]='<li id="'.$row->id.'">'.$row->text.'</li>';
}
} else {
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>
您的setinvval()
接受一个回调函数作为第一个参数。你传了一串。应该是:
setInterval(ajaxLoad, 5000);
另外,从$ajaxLoad
定义中删除$
。这是JavaScript,不是PHP。如果您想在变量前面加上$
,则还必须将该变量与$
一起使用,如下所示:
$variable = 5;
console.log($variable); // prints 5 to the console
但是,这绝对是一种糟糕的做法,因为您会对使用的是PHP还是JS感到困惑
这里你也犯了一个错误。根据当前代码,您可能只得到最后一条插入的记录,而不是所有新插入的记录,因为您没有连接这些记录。这是解决问题的一种方法:
<?php
require "config.php";
if ($_POST)
{
$lastid = $_POST["lastid"];
if (!$lastid)
{
$array["error"] = "something is wrong";
}
else
{
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows())
{
$new_rows = "";
while ($row = $query->fetch_object())
{
$new_rows .= '<li id="'.$row->id.'">'.$row->text.'</li>';
}
$array["data"]=$new_rows;
}
else
{
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>
使用此代码,您可能只会得到最后一个插入的行,而不是所有新插入的行,对吗?对于您在这个问题中输入的代码,您预计会发生哪些不发生的情况?请编辑您的问题以添加此信息。
<?php
require "config.php";
if ($_POST)
{
$lastid = $_POST["lastid"];
if (!$lastid)
{
$array["error"] = "something is wrong";
}
else
{
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows())
{
$new_rows = "";
while ($row = $query->fetch_object())
{
$new_rows .= '<li id="'.$row->id.'">'.$row->text.'</li>';
}
$array["data"]=$new_rows;
}
else
{
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>