thinkphp5 --接口实例

这是我自己构思的案例,写的不好请多多指教。

后台接口的代码:

    public function index()
    {
        $res = array();
        header("Access-Control-Allow-Origin:*");
        $page = input('get.page')?input('get.page'):1;
        $URL = 	hinkRequest::instance() -> domain();

          $data=  Db::view('Article','title,des,author,content,cateid,create_time,min_img')
                    ->view('Cate',['cate_name','desc','content'=> 'cate_content'],'Article.cateid = Cate.cate_id')
                    ->paginate(2,false,['page'=> $page]);

       if(!empty($data))
       {
           foreach($data as $k => &$v)
           {
               $v['min_img'] = $URL . __UPLOADS__ . '/' .$v['min_img'];//tp5无法修改获取的内容

               //使用一下数组的形式
                 $res[] = $v;
                 $res[$k]['min_img'] = $URL . __UPLOADS__ . '/' .$v['min_img'];
           }
//        die();

       }

//        dump($res);
//        die();

//        return json(['data'=>$data,'code'=>1,'message'=>'操作完成']);//ajax可以,但是jq不行
//        return $data -> toJson();//对应JSON.parse解析,都可以//        return json($data);//ajax可以,但是jq不行
//        return json_encode($data);//对应JSON.parse解析,都可以


        //使用一下数组的形式
//        return json(['data'=>$res,'code'=>1,'message'=>'操作完成']);//ajax可以,但是jq不行
//        return json($res);//ajax可以,但是jq不行
//        return json_encode($res);//对应JSON.parse解析,都可以
    }

前端的代码:

    <script src="./jquery-3.1.1.js"></script>
    <script>


   console.log('下面是JQ打印');

    $(function(){
        $.get("http://bicktp.com/index/Interfaces?page=2",function(res){
//            console.log(JSON.parse(res));
            console.log(JSON.parse(res));
        })
        // $.getJSON("http://www.chinafanke.com/index/Interfaces",function(json){
        //     console.log(json)
        // });
    })
   

    console.log('下面是ajax打印');

    $.ajax({
        type:"GET",
        url: "http://bicktp.com/index/Interfaces",
        data:
        {

        },
        dataType:"json",
        success:function(data)
        {
            console.log(data);
        },
        error:function(jqXHR)
        {
            alert("发生错误:" + jqXHR.status);
        }

    });
    </script>

以上的代码说jq不行啊,是因为jq的那个方法里面,多了  JSON.parse()这个方法。

而JSON.parse() 方法用于将一个 JSON 字符串转换为对象。

所以最好的方法是使用json_encode方法来json化会比较好。

刚刚我有看了一下tp5的开发手册,

发现,

所以说  $model -> toJson 和  json_encode方法的原理是一样的,所以他们都可以  JSON.parse

但是json_encode的编码格式为unicode编码

而 -> json是UTF-8编码

原文地址:https://www.cnblogs.com/laijinquan/p/9074334.html