所以,我想用来自ajax响应的html代码填充id为“listberita”的div。
这是 php 代码,其中包含带有“listberita”id 的 div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jabary - Website Budaya Jabar</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/f8535c9b97.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="berita.css">
</head>
<body>
<!-- Navbar -->
<?php include 'php/navbar.php'; ?>
<div class="container my-5">
<div class="kategoricaption mb-5">
<div class="row">
<div class="col">
<h1 class="text-center fw-bold judulkategori">Berita</h1>
<hr class="mx-auto" style="width:10%; background-color: #f49f16;">
</div>
</div>
</div>
<div class="card-group vgr-cards" id="listberita">
</div>
</div>
<!-- footer -->
<?php include 'php/footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="js/bootstrap.bundle.min.js "></script>
<script src="berita.js"></script>
</body>
</html>
这是我的ajax js代码
$(this).ready(function() {
getNews()
function getNews() {
$.ajax({
type: "GET",
url: "_php/getBerita.php",
dataType: "JSON",
success: function(response) {
var kode;
$.each(response, function(i, obj) {
console.log(kode)
kode += '<div class="card kartu pb-3"><div class="card-img-body"><img class="card-img" src="img/Berita/' + obj.gambar_berita + '" alt="Card imagecap"></div><div class="card-body"><h4 class="card-title">' + obj.nama_berita + '</h4><p class="card-text">' + obj.keterangan_berita.substring(0, 250) + '....</p><a href="isiBerita.php?id=' + obj.id + '#disqus_thread" class="btn btn-success mt-5">Read More</a></div></div>'
$('#listberita').html(kode);
})
}
});
}
})
这是我的 php 代码,其中 ajax 请求 (php_/getBerita.php)
<?php
include '../koneksi.php';
$result = $conn->query("SELECT * from tbl_berita");
while($row=$result->fetch_assoc()){
$data[]=$row;
}
echo json_encode($data);
?>
如何去掉div开头的“未定义”的东西?
尝试将您的
var kode;
更改为 var kode = "";
。
当你声明变量而不初始化它时,它将是
undefined
。然后你的循环将文本附加到 undefined
变量。大概就是这个原因。