您的位置:首页 > 编程语言 > PHP开发

thinkphp-编写第一个后台接口

2016-10-20 13:49 453 查看

安装thinkphp

讲下载好的thinkphp包放在apache的发布目录下,并起一个应用名(我这里起的名字是zero)。

路径如下:



进入到控制器目录



打开indexController.php文件

我们可对文件稍作修改

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

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


打开浏览器,输入

http://localhost/zero/

可看到



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

我们输入

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

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

编写接口

在刚才的路径下新建一个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

可以看到



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

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

打开一个包含有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);
}
});


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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thinkphp