http://server/user/getinfo
http://server/shop/getlist
http://server/shop/getLoveShop
http://server/ad/5
假设在ajax 逐条路由执行将是这样:
$.get('http://server/user/getinfo','',function(res){
},'json');
$.get('http://server/shop/getlist','',function(res){
},'json');
$.get('http://server/user/getinfo','',function(res){
},'json');
$.get('http://server/shop/getLoveShop','',function(res){
},'json');
$.get('http://server/ad/5','',function(res){
},'json');这样执行肯定没问题。我想对这些路由访问进行优化,把他们集中在一个AJAX里面执行。
执行的方法如下:
var str = 'route[]=/user/getinfo&';
str+='route[]=/shop/getlis&';
str+='route[]=/shop/getLoveShop&';
str+='route[]=/ad/5';
$.post('/route/call' , str,function(res){
},'json');
我想把他们合并起来一次执行这么多路由访问命令,现在却不知道怎么去实现。
已找到解决方案,如下代码:
后端闭包控制器,我直接写在了 application/common.php 文件中:
<?php
use think\Route;
use think\Request;
use think\App;
// 执行ad 闭包
Route::rule('/ad/:id' , function($id){
return json(['adlist'=>['1.jpg','2.jpg'],'callid:'=>$id]);
});
Route::rule('/route/call' , function(){
$routes = $_POST['route'];
// 此处截断处理
$data = [];
// 获取访问方式,HTTP或者HTTPS
$scheme = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
// 获取host路径
$host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] :
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] :
(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] :
(isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '')));
foreach($routes as $route){
// 生成 Request;
// 伪造URL变量
$uri = $route;
if($route[0] == '/'){
// 跟路径则生成访问连接
$uri = $scheme.$host.$route;
}
// 执行完这个结果后返回
$request = Request::create($uri);
// 执行伪造的 URL路径
$data[$route] = App::run($request)->getData();
}
// 返回执行完毕的数据
return json($data);
});控制器文件application/index/controller/User.php:<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class User extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
//
return json(['index'=>'user/index']);
}
/**
* 显示创建资源表单页.
*
* @return \think\Response
*/
public function create()
{
//
return json(['index'=>'user/create']);
}
}前端文件1.html:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="static/js/jquery.js"></script>
</head>
<body>
<script>
var str = {};
str.route = [];
str['route'].push('/index/user/index');
str['route'].push('/index/user/create');
str['route'].push('/ad/5');
$.post('/route/call' , str , function(res){
console.log(res);
})
</script>
</body>
</html>返回结果如下(已经过JSON格式化,):{
"/index/user/index": {
"index": "user/index"
},
"/index/user/create": {
"index": "user/create"
},
"/ad/5": {
"adlist": [
"1.jpg",
"2.jpg"
],
"callid:": "5"
}
} 最佳答案