yii2下实现ajax

22 篇文章 0 订阅
4 篇文章 0 订阅

要实现的是一个类似于手机里面的笔画输入法的功能,相应的字库已经事前准备好。

实现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”]来接收了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值