最终目的:写一个接口给我前台ajax调用
一:安装5.1.*版本
从5.1版本开始安装使用git 安装下载 这参考 5.1*版本文档即可 (注意 php5.6版本以上)
https://www.kancloud.cn/manual/thinkphp5_1/353948
学到一点 git clone https://github.com/top-think/think tp5 这个git语句后面 加了个 tp5 之前没这么用过 还有点困惑,他的功能--算是重新命名了目录的文件夹
二:出现的错误是:No input file specified
安装成功 打开默认的首页没问题,但是打开程序自带的其他模块路径 就出现 No input file specified 错误
百度得知 在域名后面加上 index.php 才可以
最终解决方法
把下面的内容保存为.htaccess文件放到应用入口文件的同级public文件目录下 代码如下:
<IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L] //其实tp5的该地方已经存在这样的文件了,只不过是在 index.php后面加了个 ? 就行 </IfModule>
修改之前:http://你的域名/index.php/home
修改之后:http://你的域名/home
三:开始 第一个接口 实现
1.数据库 表 表中的信息 这些准备好!
2.在 application 文件下 建立 api文件夹 ,在api文件夹下分别建立 controller 和 model文件夹,分别存放控制器和模型
3.编写控制器 controller 下建立 UserController.php 代码 如下
<?php namespace app\api\controller;//注意写准确命名空间 use think\Controller; class UserController extends Controller //类名字 和控制器名字一样 { public function read() { $uid = input('uid'); $model = model('User'); $data = $model->getUsers($uid);// 查询数据---模型下的方法 if ($data) { $code = 200; } else { $code = 404; } $data = [ 'code' => $code, 'data' => $data ]; return json($data); } }
4.编写模型 model下新建立User.php 代码 如下
<?php namespace app\api\model; use think\Model; use think\Db; class User extends Model{ public function getUsers($uid = 1){ $res = Db::name('users')->where('uid', $uid)->select(); // echo $this->getLastSql(); return $res; } }
5.编写路由
注意:5.1版本将路由单独拿出来了 和 application同级的
在route文件下 编写 route.php
代码
Route::rule('user/:uid','api/UserController/read'); //api模块 UserController 控制器的 read方法 Route::rule('user','api/UserController/read'); //上面两个路由写法是一个,只不过参数定义的位子不一样
6 检测效果
先用第一个路由方式 网址输入 http://www.thinkapi.com/user/1
见到如下结果
可以争取的取到数据库的信息
再用第二个路由方式 网址输入 http://www.thinkapi.com/user
见到如下结果
依然是调通的,但没有拿到参数
7.结合ajax 使用,直接上代码
var data ={"uid":'1'} var url1 = 'http://www.thinkapi.com/user/1'; var url2 = 'http://www.thinkapi.com/user'; $.ajax({ type:"post", url:"http://www.thinkapi.com/user", async:true, data:data, success:function(res){ console.log(res) }, error:function(err){ console.log(err) } }); //注意 :url1 默认后面跟了参数 //data 数据 要用json对象格式的,
浏览器ajax也能获取到数据!!
目标完成
6666