在上一個(gè)項(xiàng)目中肘迎,采用了前后端分離甥温,感覺(jué)比以前的前后端混在一起清爽許多。前后端分離妓布,使得前端和后端之間分開(kāi)姻蚓,各自互不干擾。后端負(fù)責(zé)邏輯的交互匣沼,與數(shù)據(jù)庫(kù)的連接以及提供好一個(gè)接口狰挡。前端負(fù)責(zé)從接口獲取數(shù)據(jù),控制視圖释涛。
以下是一個(gè)小的demo代碼:
后端接口
/** 請(qǐng)求數(shù)據(jù)加叁,返回json
* @return string
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function indexMap(){
if(request()->isGet()){
$ship_name = Request::instance()->param('ship_name');
$start_time = Request::instance()->param('start_time');
$end_time = Request::instance()->param('end_time');
//條件查詢
$map['cmf_ship.name'] = ['=',"$ship_name"];
$map['cmf_locus.time'] = array('between',array("$start_time","$end_time"));
$map['cmf_locus.position'] = ['=',"定位"];
$map['cmf_locus.alarm'] = ['=',"一切正常"];
$data = Db::name('locus')
->alias('a')
->join('cmf_ship b','a.ship_id = b.id','left')
->field('a.id,a.time,a.ship_id,a.latitude,a.longitude,a.speed,a.height,a.direction,b.id,b.phone,b.captain,b.name')
->where($map)
->order('time' )
->select();
return json_encode($data );
}
}
前端通過(guò)接口接收數(shù)據(jù)來(lái)控制視圖
<script>
$.get("{:url('Map/indexMap')}?ship_name={$ship_name}&start_time={$start_time}&end_time={$end_time}",function (event) {
var data = JSON.parse(event);
trackCheck(data);
})
<script>
以上、就是-前后端分離的一個(gè)小的demo