ThinkPHP的rest与普通controller可以使用一个类共用Controller,只要从RestController继承。这是与yii2不同的地方。
- <?php
- namespace Home\Controller;
- use Think\Controller\RestController;
- class HomeController extends RestController {
- protected $allowMethod = array (
- 'get',
- 'post',
- 'put'
- );
- // Rest允许的请求类型列表
- protected $allowType = array (
- 'xml',
- 'json'
- );
- Public function read_json() {
- // 输出id为1的Info的json数据
- $this->response(['a'=>'b'],'json');
- }
- }
访问:
/Home/read/.json
获取参数的方式:
- public function query($SellId){
- $Form=M('web_hm_sells');
- $data=$Form->find($SellId);
- $this->response($data,'json');
- }
- /**
- * @param int $p 第几页
- * @param int $rows 每页大小
- * page
- * /Hm/Sells/getlist/p/1/rows/5
- */
- public function getlist($p,$rows){
- $Data=M('web_hm_sells');
- $map=[];
- $count = $Data->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件
- $Page = new \Think\Page($count, $rows);// 实例化分页类 传入总记录数
- //var_dump($Page);die();
- $list = $Data->where($map)->order('SellId')->limit($Page->firstRow.','.$Page->listRows)->select();
- $this->response([
- 'd'=>[
- 'Table'=>[
- 'rows'=>$list
- ],
- 'Pagecount'=>($Page->totalRows-1)/$rows+1,
- 'Total'=>$Page->totalRows,
- 'Page'=>$p
- ]],'json');
- }
请求
- $.get('/Home/read/id/2');1
ThinkPHP要求php版本为5.3+,但如果要支持shorthand array写法,需要5.4+。
shorthand array:
$a=[‘key’=>’value’];