thinkphp-编写第一个后台接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunshao904/article/details/81216095

进入到控制器目录

控制器目录

打开indexController.php文件

我们可对文件稍作修改

<?php
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller { 

    public function index(){
        echo 'hello php';
    }
}

打开浏览器,输入

http://localhost/zero/

可看到

index

此文件为控制器的默认文件,就像在浏览器中输入文件夹名就默认访问此文件夹下的index.html

我们输入

http://localhost/zero/index.php/Home/Index/index

和刚才访问的是同一个接口,这个路径是该接口的真正路径

扫描二维码关注公众号,回复: 5854499 查看本文章

编写接口

在刚才的路径下新建一个php文件,名为TestController.class.php

代码如下:

<?php
namespace Home\Controller;
use Think\Controller;
header("Content-Type: text/html;charset=utf-8");
class TestController extends Controller { 

    public function hello(){
        echo('厉害了我的哥!');
    }
}

注意: 
- 文件的命名格式必须按照规定的格式

类名 + Controller.class.php

  • 类名首字母必须大写

  • 文件中的类名必须和文件名一致

在浏览器中输入如下地址

http://localhost/zero/index.php/Home/Test/hello

看看是不是打印出来了

ajax请求

现在我们对刚才的TestController.Class.php稍作修改,以适应于ajax数据请求。

<?php
namespace Home\Controller;
use Think\Controller;
header("Content-Type: text/html;charset=utf-8");
header('Access-Control-Allow-Origin:*');//允许跨域
class TestController extends Controller { 

    public function hello(){
        $buff -> a ='are you OK?';
        $buff -> b ='厉害了我的哥';
        $this->ajaxReturn($buff);
    }
}

在浏览器中输入如下地址

http://localhost/zero/index.php/Home/Test/hello

可以看到

ajax数据请求

汉字在这里显示是有问题的

现在我们就可以在任意页面中请求该后台接口

打开一个包含有jQuery的html页面的控制台

输入如下js代码代码

$.ajax({
    type: "get",
    url: "http://localhost/zero/index.php/Home/Test/hello?",
    data: {},
    dataType: "json",
    success: function(result){
        console.log('成功回调',result);
    },
    error: function(result,a,b){
        console.log('失败回调',result,a,b);
    }
});

看!是不是执行了成功回调函数 
ajax请求

猜你喜欢

转载自blog.csdn.net/sunshao904/article/details/81216095