View的代码
<div id="community-ajax"></div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'community')->textInput() ?>
<div class="form-group">
<label class="control-label"> </label>
<?= Html::submitButton($model->isNewRecord ? '添加' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<script>
$(document).ready(function(){
$("#second-community").on('input propertychange', function(){
$("#community-ajax").load('?r=test/ajax&str=' + $("#second-community").val(), function(){
$("p.hitp").click(function(){
$("#second-community").val($(this).text());
$("#community-ajax").css("display", "none");
});
});
$("#community-ajax").css("display", "block");
});
})
</script>
<style>
#community-ajax{
position:absolute;
border:1px solid #ccc;
background:white;
left:365px;
top:169px;
width:300px;
display:none;
}
#community-ajax p{
line-height:32px;
}
#community-ajax p:hover{
background:#eee;
}
</style>
Controller的代码
public function actionAjax($str){
$result = "";
$communities = BaseCommunity::find()->where("name like '%" . $str . "%'")->limit(10)->all();
foreach($communities as $c){
$result .= '<p class="hitp">' . $c->name . '</p>';
}
//echo $result;
return $result;
}