AJAX 是與服務器交換數據的技術,它在不重載所有頁面的狀況下,實現了對部分網頁的更新。php
html代碼:html
<td class="text-c listorder"> <input size="3" attr-id="{$vo.id}" name="listorder" value="{$vo.listorder}"/> </td>
js代碼:ajax
// 排序框失焦觸發事件(category) 添加函數到 blur 事件。當 <input> 字段失去焦點時發生 blur 事件: $('.listorder input').blur(function(){ // 排序id var id = $(this).attr('attr-id'); // 填寫的排序 var listorder = $(this).val(); var postData = { 'id' : id, 'listorder' : listorder } var url = "{:url('category/listorder')}"; // ajax 傳送信息 $.post(url,postData,function(result){ if(result.code == 1){ location.href = result.data; }else{ alert(result.msg); } },"json"); });
PHP業務邏輯:【ThinkPHP5.0】 控制器sql
/* * 公共的排序 listorder, svae更新操做。 */ public function listorder($id, $listorder) { // 獲取控制器 $model = request()->controller(); $res = model($model)->save(['listorder'=>$listorder], ['id'=>$id]); if($res) { $this->result($_SERVER['HTTP_REFERER'], 1, '更新成功'); }else { $this->result($_SERVER['HTTP_REFERER'], 0, '更新失敗'); } }
數據表:json
CREATE TABLE `listorder` ( `id` int(10) unsigned NOT NULL, `listorder` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '排序' )ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; alter table `listorder` add primary key (id);
html代碼:api
<div> <label >所屬城市:</label> <select name="city_id" class="select cityId" > <option value="0">--請選擇--</option> {volist name = "citys" id = "vo"} <option value="{$vo.id}">{$vo.name}</option> {/volist} </select> <select name="se_city_id" class="select se_city_id"> <option value="0">--請選擇--</option> </select> </div>
js代碼:【3級的話,再寫個js, 經過城市查詢縣】服務器
/** * 點擊城市獲取二級城市 */ $(".cityId").change(function(){ city_id = $(this).val(); url = "{:url('api/city/getCitysByParentid')}"; postData = { 'id' : city_id }; // 拋出請求 $.post(url,postData,function(result){ // todo if(result.status == 1){ // 將信息填充到變量 // [{id: 13, name: "吉安", uname: "jian", parent_id: 4, listorder: 0, status: 1,…},…] data = result.data; city_html = ""; $(data).each(function(){ city_html += "<option value='"+this.id+"'>"+this.name+"</option>>"; }); $('.se_city_id').html(city_html); }else if(result.status == 0){ // alert(result.message); $('.se_city_id').html(''); return; } },"json"); });
以php api接口形式編寫查詢邏輯:異步
private $obj; public function _initialize() { $this->obj = model("Category"); } public function getCategoryByParentId() { $id = input('post.id',0, 'intval'); // 經過id獲取二級城市 $categorys = $this->obj->getNormalCategoryByParentId($id); if(!$categorys) { return show(0,'沒有子分類'); } return show(1,'success', $categorys); }
模型查詢操做:函數
/** * 獲取分類數據 (admin/deal/index) */ public function getNormalCategoryByParentId($parentId=0) { $data = [ 'status' => 1, 'parent_id' => $parentId, ]; $order = [ 'id' => 'desc', ]; return $this->where($data) ->order($order) ->select(); }