网站页面通过异步ajax请求接口json数据的方式生成一个前端显示模块
环境介绍:
laravel5.5+提供api请求;
该demo是线上项目的真实例子,删除掉了一些不必要的业务逻辑代码,
这样demo看起来又简洁代码又少还能跑,完美
后端代码:
路由,在api.php文件里
//access
$api->group([
'middleware' => 'api.throttle',
'limit' => config('api.rate_limits.access.limit'),
'expires' => config('api.rate_limits.access.expires'),], function($api) {
//关联api
$api->get('askcardnews', 'DbgContr[email protected]')->name('api.dbg.askcardnews');
});
api控制器
public function askcardnews()
{
header("Access-Control-Allow-Origin: *");
$query = request()->input();
//判断
//if (!isset($query['question_id']) || !is_numeric($query['question_id'])) {return 401;}
$ask_db = DB::connection('askdb');// connection: db
...
//5条
$cardnews = DB::table('cardarticles')->select('id','title','generate_url')->orderBy('updated_at','desc')->take(5)->get()->toJson();
//5条
$cards = DB::table('CreditCard')->select('id','Name','generate_url')->orderBy('updated_at','desc')->take(5)->get()->toJson();
$res['icons'] = json_decode($cardnews,true);
$res['cards'] = json_decode($cards,true);
return json_encode($res);
}
前端代码:
<!-- s添加模块 -->
<div class="aw-mod">
<div class="mod-head"><h3>相关1</h3></div>
<div class="mod-body font-size-12">
<ul class="tab1" id="askcardnewslist"></ul>
</div>
</div>
<div class="aw-mod">
<div class="mod-head"><h3>相关2</h3></div>
<div class="mod-body font-size-12">
<ul class="tab1" id="askproductcreditcardlist"></ul>
</div>
</div>
<script type="text/javascript">
var host = "https://www.zongscan.com/api/askcardnews?question_id=110";//99
$.ajax({
url: host,
type: 'GET',
// 默认为GET
timeout: 5000,
// 超时时间
success: function success(result) {
var data = $.parseJSON(result);
getIcon(data);
getCards(data);
}
});
function getIcon(data) {
var a = "";
$.each(data.icons, function (index, item) {
a += "\n <li><a href=\"https://www.zongscan.com".concat(item.generate_url, "\" rel=\"nofollow\" target=\"_Blank\">\n <p>").concat(item.title, "</p>\n</a></li>\n ");
});
$("#askcardnewslist").append(a);
}
function getCards(data) {
var a = "";
$.each(data.cards, function (index, item) {
a += "\n <li><a href=\"https://www.zongscan.com".concat(item.generate_url, "\" rel=\"nofollow\" target=\"_Blank\">\n <p>").concat(item.Name, "</p>\n</a></li>\n ");
});
$("#askproductcreditcardlist").append(a);
}
</script>
<!-- e添加模块 -->
完
相关文章