october处理页面上ajax请求或提交数据处理
初始化
在页面,布局、或者partials中页面增加jquery
<script src="{{ 'assets/javascript/jquery.js'|theme }}"></script>
october 增加了框架自带的jquery扩展
{% framework %}
ajax处理数据
<form onsubmit="$(this).request('onProcess'); return false;">
表单提交请求,在页面的php代码区
function onProcess()
{
return request()->all();
}
通过chrome网络查看请求头信息
X-OCTOBER-REQUEST-HANDLER:onProcess
X-OCTOBER-REQUEST-PARTIALS:
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
shaizi:1
返回数据
{shaizi: "1"}
具体查看各种请访问http://octobercms.com/docs/ajax/javascript-api
实现一个石头剪子布的小游戏
创建一个partials
game/game1.htm 内容如下:
{% if result %}
<span class="lead">
<span class="label label-success">{{ result }}</span>
</span>
{% endif %}
创建一个页面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="">请选择</option>
<option value="1">石头</option>
<option value="2">剪子</option>
<option value="3">布</option>
</select>
<button type="submit" class="btn btn btn-primary">开始</button>
</form>
</div>
</div>
<!-- partials 内容 -->
<div class="panel-footer" id="result">
{% partial "game/game1" %}
</div>
</div>
<!-- 通过ajax提交数据 -->
<script>
$('.btn').click(function(){
$('form').request('onGame', {
update: {'game/game1': '#result'},
beforeUpdate:function() {
if($('select[name="shaizi"]').val() == '') {
alert('请选择后再点击开始');
}
}
});
return false;
});
</script>
在php区添加下面内容
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):'同时出' . $data[$shaizi] . ',平局';
}
效果如下: