在根目录下application/api/controller/新建一个文件Comment.php
用专业编辑器打开输入以下内容:
<?php namespace app\api\controller; use think\Db; class Comment extends Base { public function comment() { $aid = input('param.aid/d'); $users_id = (int)session('users_id'); $users_ip = clientIP(); if ($users_id > 0 || empty($users_id)) { $arc = Db::name('weapp_comment')->where([ 'users_id' => $users_id, 'aid' => $aid, 'is_review' => 1, ])->count(); } else { $arc = Db::name('weapp_comment')->where([ 'users_ip' => $users_ip, 'aid' => $aid, 'is_review' => 1, ])->count(); } $info = Db::name('article_content')->where([ 'aid' => $aid, ])->getField('自定义字段');//文件模型其他模型可以看数据库更改,此处为文章模型为例! if ($arc > 0) { $this->success('获取成功',null ,['info'=>$info]); } else { $this->error('获取失败'); } } }
html代码找到view_article.htm里面在需要显示的位置添加以下代码包含JS代码
注:样式请自己解决!
<!--HTML代码如下-->
<div id="getComment">请评论后显示</div>
<!--JS代码如下-->
<script type="text/javascript">
function getweapp_comment(aid)
{
//步骤一:创建异步对象
var ajax = new XMLHttpRequest();
//步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端
ajax.open("post", root_dir+'/index.php?m=api&c=Comment&a=comment', true);
// 给头部添加ajax信息
ajax.setRequestHeader("X-Requested-With","XMLHttpRequest");
// 如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//步骤三:发送请求+数据
ajax.send('aid='+aid+'&_ajax=1');
//步骤四:注册事件 onreadystatechange 状态改变就会调用
ajax.onreadystatechange = function () {
//步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
if (ajax.readyState==4 && ajax.status==200) {
var json = ajax.responseText;
var res = JSON.parse(json);
if (1 == res.code) {
document.getElementById('getComment').innerHTML = res.data.info;
}
}
}
}
getweapp_comment('{$eyou.field.aid}');
</script>