要实现的是一个类似于手机里面的笔画输入法的功能,相应的字库已经事前准备好。
实现ajax主要是jQuery的功能,所以关键的内容在view里面。
controller:
public function actionIndex(){
set_time_limit(0);
$zi = "汉";
$dict = new Dictation();
$pinyin = $dict->GetPronunce($zi);
$ciList = $dict->GetCis($zi);
for($i=0; $i < count($ciList); $i++){
$ciList[$i] = str_replace($zi, "( )", $ciList[$i]);
}
return $this->render('zi', [
'pinyin' => $pinyin,
'ciList' => $ciList,
]);
}
view:
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = '听写';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
<script>
$(document).ready(function(){
$("button").click(function(){
$("#spell").text($("#spell").text() + this.innerText);
$("#index").text($("#index").text() + this.id);
$("#list").load("?r=dictate/getzis" , {"spells":$("#index").text()});
});
});
</script>
<?php
// 一丨丿丶乙
echo '<br /><br /><br /><br /><br /><br /><br /><br /><br />';
echo $pinyin . '<br />';
foreach($ciList as $l){
echo $l . '<br />';
}
?>
<p id="spell"></p>
<p id="index" style="display:none";></p>
<p id="list"></p>
<button id="1" type="button">一</button>
<button id="2" type="button">丨</button>
<button id="3" type="button">丿</button><br />
<button id="4" type="button">丶</button>
<button id="5" type="button">乙</button>
<p> this is a test</p>
<?php $form = ActiveForm::begin(); ?>
<div class="button-group">
<?= Html::submitButton('提交', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
接收ajax提交并负责反馈的方法:
controller:
public function actionGetzis(){
$zi = new Zi();
$spells = $_POST['spells'];
return $zi->GetListBySpells($spells);
}
这里注意一点,因为yii2接收post数据都是用一个model类,在view里生成,然后在controller里接收。这里只接收一个数据没有必要那么麻烦,就使用了php原生的内置全局变量$_POST[“spells”]来接收了。