october處理頁(yè)面上ajax請(qǐng)求或提交數(shù)據(jù)處理
初始化
在頁(yè)面,布局黔帕、或者partials中頁(yè)面增加jquery
<script src="{{ 'assets/javascript/jquery.js'|theme }}"></script>
october 增加了框架自帶的jquery擴(kuò)展
{% framework %}
ajax處理數(shù)據(jù)
<form onsubmit="$(this).request('onProcess'); return false;">
表單提交請(qǐng)求,在頁(yè)面的php代碼區(qū)
function onProcess()
{
return request()->all();
}
通過(guò)chrome網(wǎng)絡(luò)查看請(qǐng)求頭信息
X-OCTOBER-REQUEST-HANDLER:onProcess
X-OCTOBER-REQUEST-PARTIALS:
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
shaizi:1
返回?cái)?shù)據(jù)
{shaizi: "1"}
具體查看各種請(qǐng)?jiān)L問(wèn)http://octobercms.com/docs/ajax/javascript-api
實(shí)現(xiàn)一個(gè)石頭剪子布的小游戲
創(chuàng)建一個(gè)partials
game/game1.htm 內(nèi)容如下:
{% if result %}
<span class="lead">
<span class="label label-success">{{ result }}</span>
</span>
{% endif %}
創(chuàng)建一個(gè)頁(yè)面game1.htm
<script src="{{ 'assets/javascript/jquery.js'|theme }}"></script>
{% framework %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">石頭剪子布游戲</h3>
</div>
<div class="panel-body">
<form method="post" onsubmit="$(this).request('onProcess'); return false;">
<select class="form-control" name="shaizi" style="width: 70px">
<option value="">請(qǐng)選擇</option>
<option value="1">石頭</option>
<option value="2">剪子</option>
<option value="3">布</option>
</select>
<button type="submit" class="btn btn btn-primary">開(kāi)始</button>
</form>
</div>
</div>
<!-- partials 內(nèi)容 -->
<div class="panel-footer" id="result">
{% partial "game/game1" %}
</div>
</div>
<!-- 通過(guò)ajax提交數(shù)據(jù) -->
<script>
$('.btn').click(function(){
$('form').request('onGame', {
update: {'game/game1': '#result'},
beforeUpdate:function() {
if($('select[name="shaizi"]').val() == '') {
alert('請(qǐng)選擇后再點(diǎn)擊開(kāi)始');
}
}
});
return false;
});
</script>
在php區(qū)添加下面內(nèi)容
function onGame()
{
$data = [1=>'石頭',2=>'剪子',3=>'布'];
$shaizi = post('shaizi');
$rnd = rand(1,3);
$result[12] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'您勝';
$result[13] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'電腦勝';
$result[21] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'電腦勝';
$result[23] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'您勝';
$result[32] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'電腦勝';
$result[31] = '您'. $data[$shaizi]. '電腦'.$data[$rnd] .'您勝';
$this['result'] = isset($result[$shaizi.$rnd]) ? $result[$shaizi.$rnd):'同時(shí)出' . $data[$shaizi] . ',平局';
}
效果如下:
游戲