PHP的响应可以正常工作,但在div的开头有“undefined”文本

gwo2fgha  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(98)

所以,我想用id“listberita”填充div,并使用来自aScore response的HTML代码。
下面是PHP代码,其中包含ID为“listberita”的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>

字符串
下面是我的aqjs代码

$(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代码,其中一个请求(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);

?>


上面的代码是工作,它的返回数据我想要的.但有一个问题. Here is the problem
如何去掉div开头的“undefined”?

gudnpqoy

gudnpqoy1#

var kode;更改为var kode = "";
当你声明变量而没有初始化它时,它将是undefined。然后你的循环将文本附加到undefined变量上。这可能就是原因。

相关问题