【问题标题】:How to add a PHP model as source to jQuery autocomplete source?如何将 PHP 模型作为源添加到 jQuery 自动完成源?
【发布时间】:2021-12-08 22:02:21
【问题描述】:

伙计们。

我需要一些帮助。我正在尝试将 jQuery 自动完成添加到 PHP 表单中。我有自动完成设置,并且使用数组它工作得很好。但是,当我尝试将 PHP 模型用于 postgreSQL 数据库时,它不起作用。

模型本身是用 PHP 和 Yii1.1 框架编写的。 “Tag.php”看起来像这样:

<?php

/**
 * This is the model class for table "tag".
 *
 * The followings are the available columns in table 'tag':
 * @property string $idtag
 * @property string $tag
 *
 * The followings are the available model relations:
 * @property Dashboard[] $dashboards
 */
class Tag extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'tag';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('tag', 'required', 'message'=>'Please enter a tag'),
            array('tag', 'type', 'type'=>'string'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('idtag, tag', 'safe', 'on'=>'search'),
        );
    }

    /*
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'dashboards' => array(self::MANY_MANY, 'Dashboard', 'dashboard_has_tag(fk_idtag, fk_iddashboard)'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'idtag' => Yii::t('idtag', 'Tag ID'),
            'tag' => Yii::t('tag', 'Tag name'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('idtag',$this->idtag,true);
        $criteria->compare('LOWER(tag)',strtolower($this->tag),true);

        return new CActiveDataProvider($this, array('criteria'=>$criteria));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Tag the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

以下代码是我尝试实际设置 jQuery 自动完成的方式:

<script type="text/javascript">
$(function() {
    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }
 
    // When selecting an item with the tab key, it wont move away from the text area.
    $("#tag_text").on("keydown", function(event) {
        if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
            event.preventDefault();
        }
    }).autocomplete({
        source: function(request, response) {
            $.getJSON("Tag.php", {
            term: extractLast(request.term)}, response);
        },
        search: function() {
            // Custom min Length for the Tags to be searched.
            var term = extractLast(this.value);
            if (term.length < 2) {
                return false;
            }
        },
        focus: function() {
            // Prevents the insertion of a value as soon as one clicks it or selects it with the key.
            return false; 
        },
        select: function(event, ui) {
            var terms = split(this.value);
            // Remove the current user input.
            terms.pop();
            // Add the selected item.
            terms.push(ui.item.value);
            // Add a placeholder to get comma and space at the end.
            terms.push("");
            this.value = terms.join(", ");
            return false;
        }
    });
});
  </script>

正如我所说,如果我将源与普通数组一起使用,它就可以正常工作。但是,我确实需要从 postgreSQL 数据库中获取数据。如果有人能帮我解决这个问题,我将不胜感激。

编辑: 我一直试图让它工作,但直到现在它根本不起作用。至少不正确。 我根本无法让我的 JS 上班。到目前为止,PHP 部分似乎工作正常,但是 JS 不会在将进行用户输入的 textarea 字段中显示任何数据。 另一件事是我并没有真正得到响应数据。下面是调用PHP函数的url。

在这里我们看到我没有任何响应数据。但是,我真的不知道为什么会这样。

【问题讨论】:

    标签: javascript php jquery postgresql


    【解决方案1】:

    您需要在两者之间放置一个CController,如下所示。 我不知道yii1,但我尽力了:

    class TagController extends CController
    {
        public function actionFind($term = null)
        {
            $tags = Tag::model()->findAll('tag LIKE :term', array(':term'=>$term));
            $data = array();
            foreach ($tags as $tag) {
                $data[$tag->tagid] = $tag->tag;
            }
            return json_encode($data);
        }
    }
    

    在 JS 中你调用控制器。

    【讨论】:

    • 非常感谢@simialbi。我在控制器中有一个动作。显然我没有检查我是否在那里犯了任何错误。我一定会试试你的功能。
    • 我已经修改了我的控制器以使其更好地满足我的需要。然而,现在我的 JS 函数并没有完成它的工作。我认为我对该函数的调用似乎很糟糕。我使用$.getJson( &lt;?php echo "'".Yii::app()-&gt;homeUrl.'?=path/to/action/Find'."'" ?&gt;, {term: extractLast(request.term)}, response) 但是,我的 JS 没有显示自动完成功能(我在数据库中有两个条目,一个名为 Test,一个名为 Blue)。我根本看不出我在哪里犯了错误。
    • 生成的代码是什么样的?浏览器开发工具中的网络标签是什么意思?路线正确吗?
    • 控制器中的$data在使用print_r()打印时如下所示:Array( [1] =&gt; Test [2] =&gt; Blue )请求URL返回一个代码为200的GET方法。当@987654327时响应返回如下@使用:ƒ (){return a.apply(b||this,c.concat(d.call(arguments)))}
    • 生成的js代码是什么样的? console.log的结果打印函数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2013-06-22
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多