PHP如何和HTML代码分离?

<?php
include "db.php";
if(isset($_POST["category"])){

    $category_query = "SELECT * FROM categories";

    $run_query = mysqli_query($con,$category_query); 
    echo "
    <div class='nav nav-pills nav-stacked'>
    <li class='active'><a href='#'><h4>Categories</h4></a></li>
    ";
if(mysqli_num_rows($run_query)>0){
    
        while($row = mysqli_fetch_array($run_query)){
            $cid = $row["cat_id"];
            $cat_name = $row["cat_title"];
            echo "
<li><a href='#' class='category' cid='$cid'>$cat_name</a></li>
            ";
        }
        echo "</div>";
    }
}
?>
//JS
$(document).ready(function() {
    cat();
    function cat() {
        $.ajax({
                url: 'action.php',
                type: 'POST',
                data: {
                    category: 1
                }
            })
            .done(function(data) {
                //console.log(data);
                $("#get_category").html(data);

            });
    }
})

php是小白,有没有办法前后端分离,把echo的HTML代码返回json的格式给前端处理?

查看回复