tp5 API 测试

index控制器--从数据库获取值

<?php

namespace app\index\controller;

class Index
{
    public function api($title = ‘‘)
    {
        if (!$title) {
            $data = model(‘Shici‘)->find();
        } else {
            $data = model(‘Shici‘)::getBytitle($title);
        }
        // return "<div><h2>".$data[‘content‘]."</h2></div>";
        return  json($data);
        // dump($data);
    }
}

user控制器  对外接口

<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class User extends Controller
{
    public function index()
    {
        return view();
    }
    public function capi()
    {
        $url = "http://apitest.so/index/index/api/";
        $ch = curl_init($url . ‘?title=‘ . input(‘title‘)); //初始化curl会话
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //将curl会话执行的结果不输出,以数据流的形式保存起来 1表示不返回bool值
        // $data = curl_exec($curl);
        $data = json_decode(curl_exec($ch), true); //执行会话,将结果保存到$data中 以数组形式返回结果
        curl_close($ch); //关闭会话
        return $data;
        // $curl = curl_init();
        // curl_setopt($curl, CURLOPT_URL, $url. ‘?title=‘ . input(‘title‘));
        // curl_setopt($curl, CURLOPT_HEADER, 0); //不抓取头部信息。只返回数据
        // curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //1表示不返回bool值
        // // $data = curl_exec($curl);
        // $data=json_decode(curl_exec($curl),true);
        // curl_close($curl); //关闭会话
        // return $data;
        // // dump($data);

    }
}

html部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div>api接口测试</div>
    <form>
        <input type="text" name="title">
        <input type="button" value="提交查询" id="test">
    </form>
    <br>
    <div id="show" style="width: 500px;margin: 0 auto;"></div>
    <script src="__JS__/jquery-3.4.1.js"></script>
    <script>
        $(function () {
            $(‘#test‘).click(function () {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "http://apitest.so/index/user/capi",
                    data: $(‘form‘).serialize(),
                    success: function (res) {
                        console.log(res);
                        console.log(typeof (res));
                        var data = "<div style=‘text-align:center‘><h3>" + res.title + "</h3></div><div style=‘text-align:center‘><h6>" + res.dynasty+":"+res.author + "</h6></div><div style=‘text-align:center‘><h4>" + res.content + "</h4></div>";
                        $(‘#show‘).html(data);
                    }
                });
            })
        })
    </script>
</body>

</html>

相关推荐