ThinkPHP 3.2 內建 ajaxReturn() 方法,配合前端 jQuery 或框架自帶 ThinkAjax 類庫,可快速實現非同步互動。本文提供兩種完整範例。
<?php
class MessageAction extends Action {
public function index() {
$this->display();
}
public function add() {
$m = M('message');
if ($m->add($_GET)) {
$this->ajaxReturn($_GET, '新增成功', 1); // data, msg, status
} else {
$this->ajaxReturn(0, '新增失敗', 0);
}
}
}
<html>
<head>
<script src="__PUBLIC__/js/jquery-1.7.1.min.js"></script>
<script>
$(function(){
$('input:button').click(function(){
var title = $('input[name="title"]').val();
var message = $('input[name="message"]').val();
var $mess = $('#mess');
$.getJSON('__URL__/add', {title: title, message: message}, function(json){
if (json.status == 1) {
$mess.slideDown(3000).html('標題為 ' + json.data.title + ' 內容為 ' + json.data.message);
} else {
$mess.slideDown(3000).html('新增失敗,請檢查');
}
});
});
});
</script>
</head>
<body>
<div id="mess" style="display:none; color:red;"></div>
<form>
標題:<input name="title"><br/>
內容:<input name="message"><br/>
<input type="button" value="提交">
</form>
</body>
</html>
public function addtwo() {
$m = M('message');
if ($vo = $m->create()) {
if ($m->add()) {
$this->ajaxReturn($vo, '新增成功', 1);
} else {
$this->ajaxReturn(0, '新增失敗', 0);
}
} else {
$this->error($m->getError());
}
}
<script src="__PUBLIC__/Js/Base.js"></script>
<script src="__PUBLIC__/Js/prototype.js"></script>
<script src="__PUBLIC__/Js/mootools.js"></script>
<script src="__PUBLIC__/Js/ThinkAjax.js"></script>
<script>
function add() {
ThinkAjax.sendForm('frm', '__URL__/addtwo', wc);
}
function wc(data, status) {
if (status != 1) alert('發送失敗');
else $('list').innerHTML += '標題' + data.title + ',內容' + data.message;
}
</script>
<body>
<div id="list"></div>
<form id="frm" method="POST">
標題:<input name="title"><br/>
內容:<input name="message"><br/>
<input type="button" value="提交" onclick="add()">
</form>
</body>
| 項目 | jQuery 方式 | ThinkAjax 方式 |
|---|---|---|
| 相依套件 | jQuery | Prototype + MooTools + ThinkAjax |
| 資料格式 | JSON | JSON(內部解析) |
| 表單序列化 | 手動取值 | ThinkAjax.sendForm 自動序列化 |
| 現代適用度 | 高 | 低(Prototype/MooTools 已過時) |
新專案**統一使用 jQuery/Vue/React + axios/fetch** 呼叫 Controller 回傳 JSON,勿再依賴框架內建 JS 類庫。