{ "api version": 0.1, "method": "object.method", "params": { "user id": 1234 } }
{ "api_v": "0.1", "reqs": [ { "name": "my_important_request", "method": "user.kick_out", "params": { "id": "1234", "when": "now", ... } }, ... ] }
<?php // @package 'api_0.1.php' // API 0.1 class API { private $last_resp; // private $resp = []; // public function __call( $method, $params ) { // , $object = substr($method, 0, strpos($method, '.')); $method_name = substr($method, strpos($method, '.')+1); // include_once __DIR__.'/source/'.$object.'.methods.php'; // $resp = $object::$method_name($params); if(!empty($resp)) $this->last_resp = $resp; else $this->last_resp = null; } // - pulbic function add_resp($req_name){ if($this->last_resp === null) return false; $req = $this->last_resp; $this->resp[$req_name] = $req; } // , public function response(){ exit ( json_encode($this->resp) ); } }
<?php class object{ function method($params){ /* ... */ } }
<?php // @package api.php header('Content-Type: application/json'); // json $api_v = $_POST['api_v']; // $path = __DIR__.'/APIs/api_'.$api_v.'.php'; // , if(!file_exists($path)) exit; // include_once __DIR__.'/APIs/api_'.$api_v.'.php'; // API $api = new API(); $reqs = $_POST['reqs']; $reqs = @json_decode($reqs, true); // json php () // , API foreach ($reqs as $req) { $method = $req['method']; $params = $req['params']; $req_name = $req['name']; $api->$method($params); $api->add_resp($req_name); } // $api->response();
function api_call(reqs, callback){ // ( , , ) json var json = JSON.stringify( (Array.isArray(reqs) ? reqs : [reqs]) ); // POST $.post({ url: '/api/api.php', // api.php dataType: 'json', // json, data: ({ api_v: '0.1', reqs: json }), // API ( json ) success: function(res){ // window, . for(var key in res){ window.loaded[key] = res[key]; } // callback(res); } }); }
Source: https://habr.com/ru/post/446348/
All Articles