thinkphp5 简单API接口开发

ThinkPHP5开发Api接口简单实例

这个实例实现这样一个功能: 
前端提交学生学号(sno)给Api Api接口返回此学生的基本信息

API接口端

<?php 
namespace app\index\controller;
use think\Controller;
use app\index\model\Student;

class User
{

    public function index() {
        return $this->fetch();
    }


    // 客户端提交学生学号(sno)给api    api返回此学生的基本信息

    public function api($sno='0001') {

        // 查询 并把数据赋值给 $data
        $data = Student::getBysno($sno);
        // 返回数据
        return json($data);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

(请求端) HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TP5通过API查询数据</title>
</head>
<body>
    <form action="http://localhost/index.php/index/user/capi/" method="post">
        <input type="text" name="sno">
        <input type="submit" value="提交查询">
    </form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(请求端) C层控制器

<?php 
namespace app\index\controller;
use think\Controller;
class User extends Controller {

    public function index() {
        return $this->fetch();
    }


    public function capi() {

        // http协议请求
        $url = 'http://localhost/index.php/index/index/api/';
        // input('sno') 是前端的from传过来的name值
        $ch = curl_init($url.'?sno='.input('sno'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行 并把执行后的数据赋值给 $data
        $data = curl_exec($ch);
        // 关闭
        curl_close($ch);
        // 返回数据
        return $data;
    }

}

猜你喜欢

转载自blog.csdn.net/heyuqing32/article/details/80966634