牛骨文教育服务平台(让学习变的简单)
博文笔记

ThinkPHP5开发Api接口简单实例

创建时间:2017-12-26 投稿人: 浏览次数:3228

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

API接口端

<?php 
namespace appindexcontroller;
use thinkController;
use appindexmodelStudent;

class User
{

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


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

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

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

}

(请求端) 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>

(请求端) C层控制器

<?php 
namespace appindexcontroller;
use thinkController;
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;
    }

}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。