根据表单(input)值变化不刷新从服务器端读取数据显示下拉列表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/carrousel0516/article/details/79946560

View的代码

<div id="community-ajax"></div>
    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'community')->textInput() ?>
    <div class="form-group">
        <label class="control-label">&nbsp;</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;
    }
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页