這是我自己構思的案例,寫的不好請多多指教。
后台接口的代碼:
public function index() { $res = array(); header("Access-Control-Allow-Origin:*"); $page = input('get.page')?input('get.page'):1; $URL = \think\Request::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編碼