在 ajax 裡遍歷 顯示資料 到頁面
阿新 • • 發佈:2018-12-21
控制器
public function search() { $data = $_POST; $search = $data['name']; // 模糊查詢 $result = DB::name('biaoqian')->where('biaoqian_name','like',"%".$search."%")->select(); / if($result) { $returnData = ['code'=>3, 'shuju'=>$result,'info'=>'成功']; }else{ $returnData = ['code'=>4, 'shuju'=>$result,'info'=>'失敗']; } return json_encode($returnData,JSON_UNESCAPED_UNICODE); echo $returnData; die; }
html 頁面
<table class="table"> <tr> <th>ID</th> <th>分類名稱</th> <th>編輯</th> <!-- <th>新增</th> --> <th>刪除</th> </tr> {foreach $biaoqian as $v} <!-- // 這是迴圈不能加id = "tableT",要不每個tr出來都是一樣的id,會報錯 --> <tr class='tableT'> <td class="center">{$v.id}</td> <td>{$v.biaoqian_name}</td> <td class="center"> <a href="admin/biao/edit_page?edit_id={$v.id}" title="編輯" class="link_icon">e</a> </td> <!-- ajax 刪除 --> <td class="center"> <a href="javascript:;" delete_id="{$v['id']}" id="delete" title="刪除" class="link_icon">d</a> </td> </tr> {/foreach} </table>
js 中
<script type="text/javascript"> $("#searchbutton").click(function(){ var name = document.getElementById('search').value; // alert(name); $.ajax({ url:'admin/biao/search.html', type:'POST', data:{ "name": name, }, dataType:'json', success:function(data){ var data2 = JSON.parse(data); var item = ""; $(".table").empty(); //清空 for(var i = 0 ; i < data2.shuju.length; i++) { item += "<tr><td>"+data2.shuju[i].id+"</td><td>"+data2.shuju[i].biaoqian_name+"</td><td class='center'><a href='admin/biao/edit_page?edit_id="+data2.shuju[i].id+"' title='編輯' class='link_icon'>e</a></td><td class='center'><a href='javascript:;' delete_id="+data2.shuju[i].id+" id='delete' title='刪除' class='link_icon'>d</a></td></tr>"; // item += "<tr><td>"+data2.shuju[i].id+"</td><td>"+data2.shuju[i].biaoqian_name+"</td></tr>"; } $(".table").append(item); // 顯示到裡面 }, error:function(data){ alert(222); console.log(data); } }) })