Home  >  Article  >  Backend Development  >  How to separate PHP from HTML code?

How to separate PHP from HTML code?

WBOY
WBOYOriginal
2016-09-06 08:57:111361browse

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

I am new to PHP. Is there any way to separate the front-end and back-end and return the echo HTML code in json format to the front-end for processing?

Reply content:

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

I am new to PHP. Is there any way to separate the front-end and back-end and return the echo HTML code in json format to the front-end for processing?

With just a few lines of code, you can separate the interface and logic and implement 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里</body>前面</code>

<code>PHP中</code>
<code>echo json_encode($html);</code>
<code>前端</code>
<code>success: function(data) {
    $("#get_category").html(data);
}</code>

PHP does this, put it in a separate file, and js can request this file

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

    $category_query = "SELECT * FROM categories";

    $run_query = mysqli_query($con,$category_query); 
    $html="";
    $html.="<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"];
            $html.="<li><a href='#' class='category' cid='$cid'>$cat_name</a></li>";
        }
        $html.="</div>";
        echo $html;
    }
}
?></code>

Convert the data found in the database into an array, output it under json_encode, call it with js, get the data, traverse the array with js (in the done of ajax that splices the html), and splice the html, so that php and html are completely separated

I think we can first determine what content we want to display on the front-end page. Assume that the content is available and the page is written based on the content. The rest is the data corresponding to the content.
As mentioned above, PHP provides an API interface, such as returning json data, and the data inside can be requested from the server through ajax. After getting the data, just use js to fill the data into the page.

I think you may be thinking about a question. It's just an issue with the output list, right? This can be done simply
After sending ajax to the front end, the front end gets the json object and can use the front end template engine to do it. Recommend you to use juicer

<code><script id="tpl" type="text/template">
    <ul>
        {@each list as it,index}
            <li>${it.name} (index: ${index})</li>
        {@/each}
        {@each blah as it}
            <li>
                num: ${it.num} <br />
                {@if it.num==3}
                    {@each it.inner as it2}
                        ${it2.time} <br />
                    {@/each}
                {@/if}
            </li>
        {@/each}
    </ul>
</script>

Javascript 代码:

var data = {
    list: [
        {name:' guokai', show: true},
        {name:' benben', show: false},
        {name:' dierbaby', show: true}
    ],
    blah: [
        {num: 1},
        {num: 2},
        {num: 3, inner:[
            {'time': '15:00'},
            {'time': '16:00'},
            {'time': '17:00'},
            {'time': '18:00'}
        ]},
        {num: 4}
    ]
};

var tpl = document.getElementById('tpl').innerHTML;
var html = juicer(tpl, data);</code>

Backend:
To return json format: You have to put the html you want to return into an array, for example:
$json = array(
'html' => $html
);

echo $json;

Front-end accepts:
$.ajax(
success: function(json){

<code>$("#get_category").html(json['html']);</code>

}
);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn