文章主要介紹了Thinkphp5框架ajax接口實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了thinkPHP5 ajax交互相關(guān)操作技巧,需要的朋友可以參考下
前一篇講到thinkphp5從數(shù)據(jù)庫獲取數(shù)據(jù)之后賦給視圖view ,前一篇從數(shù)據(jù)渲染方式來說是服務(wù)端數(shù)據(jù)渲染,這一章則是瀏覽器端數(shù)據(jù)渲染。按照知識總結(jié)依據(jù)來劃分,這是兩種不同的技術(shù)場景。
下面介紹具體的ajax接口實(shí)現(xiàn)代碼。
首先是html代碼部分,我的訪問地址為:http://app.write.com/thinkphp/public/index.php/index/index/api,這里沒有省略入口文件,同時我本地的域名是app.write.com,tp5框架在thinkphp文件里面。這里采用原生ajax,沒有做ie瀏覽器的兼容性,代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax調(diào)用接口</title>
</head>
<body>
11111
<div id="test">
</div>
<script type="text/javascript">
var oAjax = new XMLHttpRequest();
oAjax.open('GET',"/thinkphp/public/index.php/index/index/apiapi?name=1");
oAjax.onreadystatechange = function() {
if (oAjax.readyState == 4) {
if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {
console.log(oAjax.responseText);
var data=JSON.parse(oAjax.responseText);
document.getElementById("test").innerHTML=data.sex;
} else {
console.log(oAjax.status);
}
}
};
oAjax.send();
</script>
</body>
</html>
對上述代碼做一下解釋,算是一個小知識點(diǎn):一般來說可以將http狀態(tài)代碼為200作為成功的標(biāo)志,此時responseText的屬性的內(nèi)容已經(jīng)就緒。此外狀態(tài)304表示請求的資源并沒有被修改,可以直接使用瀏覽器中緩存的版本。
至于為啥是大于200是出于兼容性的考慮,有的瀏覽器會報告204。
后端代碼如下,后端代碼是同一個模塊index下的同一個控制器下index的apiapi方法。
<?php
namespace app\index\controller;
//use think\Db;
use think\Controller;
class Index extends Controller
{
public function apiapi(){
$name=$this->request->param();
return json_encode($name);
///return "common";
}
public function api(){
return view();
///return "common";
}
}
代碼首先獲取ajax獲取的參數(shù),之后返回到前端。
- Thinkphp5框架實(shí)現(xiàn)獲取數(shù)據(jù)庫數(shù)據(jù)到視圖的方法
- Web端進(jìn)行PHP代碼函數(shù)覆蓋率測試的解決方案
- PHP開發(fā)者應(yīng)該學(xué)習(xí)、會用10個PHP7新特性
- 使用者PHP圖表包裝程序創(chuàng)建漂亮的圖表的方法
- PHP單例模式模擬Java Bean實(shí)現(xiàn)方法示例詳解
- PHP圖像處理繪圖、水印、驗(yàn)證碼、圖像壓縮技術(shù)實(shí)例總
- PHP實(shí)現(xiàn)高清晰度無損圖片壓縮功能的代碼
- 用PHP處理png圖片白色背景色改為透明色的實(shí)例代碼
- 關(guān)于PHP往mysql數(shù)據(jù)庫中批量插入數(shù)據(jù)實(shí)例教程
- Php兩點(diǎn)地理坐標(biāo)距離的計(jì)算方法和具體代碼
分享到:
投訴收藏