使用tp写接口

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

   // public $defaultMethod = 'post';
   // public $allowType = ['html'];
  //  public $defaultType = 'json';
    public function index(){
        echo 'I am index';exit;
    }
    public function test1()
    {
       $html = '<span style="color:red">aaa</span>';
        $this->response($html,'html');
    }
    public function test2() {
        $id = I('get.id');
        $status = I('get.status');
        $data = [$this->_method,$this->_type,$_GET];
        header('Access-Control-Allow-Origin:http://localhost');
        header('Access-Control-Allow-Methods:POST');

        $this->response($data,'json');
    }
    public function test3() {
        $data = [$this->_method,$this->_type,$_GET];
        header('Access-Control-Allow-Origin:http://localhost');
        header('Access-Control-Allow-Methods:POST');

//        $this->response($data,'json');
        $this->ajaxReturn($data,'jsonp');

    }
}

后台代码中控制器继承RestController,设置资源类型,请求方法等。在跨域请求中设置header头部允许跨域请求,测试中设置Access-Control-Allow-Methods无效,不知道为什么。如果是jsonp请求,就用$this->ajaxReturn($data,'jsonp');

<!DOCTYPE html>
<html>
<head>
    <title>test tp api</title>
    <script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>

</head>
<body>
<input  type="button" value="button" οnclick='test()'>
<input type="button" name="" value="jsonp" οnclick="testjsonp()">
<script type="text/javascript">
function test(){
    $.ajax({
        type:'GET',
        url:'http://www.tp.com/home/api/t2/333?aa=323',

        //data:{data:'abc'},
        // beforeSend:function(request){
        //         request.setRequestHeader('Origin','songzhiwen');//此处可以获取请求对象设置头部信息
        //     },
        success:function(data){
            console.log(data);
        },
    })
}
// Access-Control-Allow-Origin   Origin
// 
function testjsonp(){
    $.ajax({
    type:'post',
    url:'http://www.tp.com/home/api/test3',
    jsonp:'callback',
    data:{a:1,b:2},
    dataType:'jsonp',
    success:function(data){
            console.log(data);
    }
    })
}
</script>
</body>
</html>

 

路由配置

'URL_MODEL' => 2,
    'URL_ROUTER_ON' =>true,
    'URL_ROUTE_RULES' => [
        'api/t1'=>['api/test1'],
        'api/t2/[:id]'=>['api/test2','status=1',['ext'=>'']],
//        'api/t3'=>['api/test3','status=1',['ext'=>'']],
    ],

可设置可选参数,额外参数,请求后缀限制,请求方法限制

转载于:https://my.oschina.net/u/2618337/blog/745400

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值