Categories
";if(mysqli_num_rows($run_query)>0){ while($row = mysqli_fetch_array($run_query)){ $cid = $row["cat_id"]; $cat_name = $row["cat_title"]; echo "$cat_name "; } echo ""; }}?>
//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的格式給前端處理?
回複內容:
Categories
";if(mysqli_num_rows($run_query)>0){ while($row = mysqli_fetch_array($run_query)){ $cid = $row["cat_id"]; $cat_name = $row["cat_title"]; echo "$cat_name "; } echo ""; }}?>
//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的格式給前端處理?
寥寥幾行代碼就可以分離介面和邏輯,實現MVC:
/index.php (頁面控制器)if(!defined('ROOT')) define('ROOT', __DIR__);require ROOT.'/include/common.php';echo render('index.php'); //輸出HTMLecho 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裡前面
PHP中
echo json_encode($html);
前端
success: function(data) { $("#get_category").html(data);}
php作這樣處理,單獨放到一個檔案,js向這個檔案請求就可以了
Categories
"; if(mysqli_num_rows($run_query)>0){ while($row = mysqli_fetch_array($run_query)){ $cid = $row["cat_id"]; $cat_name = $row["cat_title"]; $html.="$cat_name"; } $html.=""; echo $html; }}?>
資料庫裡的查出來轉成數組,json_encode下輸出,js調用,取到資料,js遍曆下數組(拼接html的ajax的done裡),拼接下html,這樣php和html就完全分開了
我覺得可以先確定前端頁面想要展示哪些內容。假設這些內容有了啊,基於這些內容寫好頁面,剩下的就是這些內容對應的資料。
而php就像樓上所說的,提供一個api介面,比如返回json資料,裡面的資料就可以通過ajax來向伺服器請求。拿到資料後用js填充資料到頁面裡面去就好了。
我覺得你可能在想一個問題。就是輸出資料行表問題對吧。這個可以簡單做
ajax給前端後,前端拿到json對象,可以用前端模板引擎來做。推薦你用juicer
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);
後端:
要想返回 json 格式: 你得把你想要返回的 html 弄到一個數組裡面 ,例如:
$json = array(
'html' => $html
);
echo $json;
前端接受:
$.ajax(
success: function(json){
$("#get_category").html(json['html']);
}
);