我想通过点击加载帖子,我有两个文件
我正在学习AJAX。我理解这项技术,因此通过单击按钮应该发生Ajax请求,然后处理程序将数据返回到Ajax请求,并且Ajax查询输出此数据。但我做不到,为什么?如何修复错误?我的错误是帖子没有加载。控制台是空的。我将echo设置为处理程序的顶部,但它不起作用。我猜是ajax的问题
index.php with ajax
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
</head>
<body>
<main>
<!-- <article class="news">
<div class="picture"><img src="1news.jpg" width="300" height="300"></div>
<div class="aboutpost">
<h2 class="aboutpost-title">Пожар в торговом центре в Кемерово</h2>
<p class="aboutpost-description">Холдинг, куда входило ЧОП "Зимней вишни", прекратил работу после трагедии</p>
</div>
</article> -->
<?php
require 'infofordb.php';
$link = mysqli_connect($host, $user, $password, $database) or die("Ошибка " . mysqli_error($link));
$query ="SELECT * FROM news ORDER BY id DESC LIMIT 5";
$result = mysqli_query($link, $query) or die("Ошибка " . mysqli_error($link));
$articles = array();
while($row = mysqli_fetch_assoc($result)) {$articles[] = $row;}
foreach($articles as $article) {echo '
<article class="news">
<div class="picture">
<img src="/image/'.$article[path].'">
</div>
<div class="aboutpost">
<h2 class="aboutpost-title">'.$article[title].'</h2>
<p class="aboutpost-description">'.$article[description].'</p>
</div>
</article>';}
?>
<center><button id="load">Загрузить ещё</button></center>
<script>
$(document).ready(function(){
var inProgress = false;
var start = 5;
$('#load').click(function() {
$.ajax({
url: 'handler.php',
method: 'POST',
data: {"start" : start},
dataType: 'json',
beforeSend: function() {inProgress = true;}
}).done(function(data){
data = jQuery.parseJSON(data);
alert('nen');
if (data.length > 0) {
//надо вывести
$.each(data, function(index, data){
$('main').append(
'<article class="news"><div class="picture"><img src="/image/' + data.path +
+ '"></div><div class="aboutpost"><h2 class="aboutpost-title">' + data.title +
+ '</h2><p class="aboutpost-description">' + data.description +
+ '</p></div></article>');
});
inProgress = false;
start += 5;
}
});
});
});
</script>
</main>
</body>
</html>
handler.php
<?php
include(infofordb.php);
$start = $_POST['start'];
$link = mysqli_connect($host, $user, $password, $database) or die("Ошибка " . mysqli_error($link));
$query ="SELECT * FROM news ORDER BY id DESC LIMIT {$start}, 5";
$result = mysqli_query($link, $query) or die("Ошибка " . mysqli_error($link));
$articles = array();
while($row = mysqli_fetch_assoc($result)) {$articles[] = $row;}
echo json_encode($articles);
?>
答案 0 :(得分:0)
dataType: 'json',
告诉jQuery解析返回的JSON数据。在您的代码中,您调用JSON.parse尝试再次解析它,删除该行(这一行我的意思是data = jQuery.parseJSON(data);
)。
答案 1 :(得分:0)
您需要在handler.php中检查您的mysql查询
$query ="SELECT * FROM news ORDER BY id DESC LIMIT {$start}, 5";
大括号在查询中不起作用。可能这可以解决你的问题。