<?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