TP5开发API接口-1.创建token、解决跨域、设置api接口返回格式
1、解决TP5接口跨域问题
说明:调用其他方法,会先执行TP5.0析构方法,然后再执行其他方法
//解决跨域--析构方法
protected function _initialize()
{
header('content-type:text/html;charset=utf-8');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
ksort($_POST);
ksort($_GET);
}
![](http://upload-images.jianshu.io/upload_images/17606291-e14fd1a36cf439a9.png?imageMogr2/auto-orient/strip|imageView2/2/w/537/format/webp)
a3e0fe5fa47ba1ca5046c74d1857ce5e.png
2、创建token方法
//生成token操作
public function create_token(){
$token = md5(mt_rand(111111,999999).time());
return $token;
}
![](http://upload-images.jianshu.io/upload_images/17606291-466bb2b31d2ddd36.png?imageMogr2/auto-orient/strip|imageView2/2/w/667/format/webp)
f669df7a90626d7a5e423904c1c04cc7.png
3.定义api接口返回数据格式,在common.php公共文件中配置
//API数据返回接口,统一规定,-1:未登录,0:普通错误,1:返回成功
function ajaxmsg($msg = "", $status = 1, $data = '', $errcode = '')
{
$json['msg'] = $msg;
$json['status'] = $status;
$json['data'] = $data;
if ($errcode) {
$json['errcode'] = $errcode;
}
echo json_encode($json, true);
exit;
}