How to separate PHP from HTML code?
<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>
}
);

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.
