首页  >  文章  >  后端开发  >  javascript - PHP如何和HTML代码分离?

javascript - PHP如何和HTML代码分离?

WBOY
WBOY原创
2016-09-06 08:57:111396浏览

<code><?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 "";
    }
}
?></code>
<code>//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);

            });
    }
})</code>

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

回复内容:

<code><?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 "";
    }
}
?></code>
<code>//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);

            });
    }
})</code>

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

寥寥几行代码就可以分离界面和逻辑,实现MVC:

<code>/index.php (页面控制器)
if(!defined('ROOT')) define('ROOT', __DIR__);
require ROOT.'/include/common.php';
echo render('index.php'); //输出HTML
echo json_encode(array('Server'=>'PHP')); //输出JSON

/include/common.php (公共操作)
if(!defined('ROOT')) exit();
require ROOT.'/include/funclass.php';

/include/funclass.php (函数和类)
if(!defined('ROOT')) exit();
function render($view) {
    ob_end_clean();    ob_start();
    require ROOT.'/view/'.$view;
    $html = ob_get_contents();
    ob_end_clean(); ob_start();
    return $html;
}

/view/index.php (视图)
require __DIR__.'/header.php'; //if(!defined('ROOT')) exit();
require __DIR__.'/footer.php'; //JS代码一般写在footer.php里</code>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn