使用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');javascript

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

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

        //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>html

 

路由配置java

'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'=>'']],
    ],

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

相关文章
相关标签/搜索