1

我正在使用 select 2 插件来搜索用户。一切都在运行,我的 jsons 最终得到:[{"id":"1","text":"Alex Fagard (afagard) ID: 1"}].etc。

我正在使用以下代码来构建选择 2 界面:

$(document).ready(function(){
   $('#username-search').select2({
    minimumInputLength: 2,
    select: function(event, ui) {
        AutoCompleteSelectHandler(event, ui)
    },
    ajax: {
      url: "classes/search.class.php?sType=users",
      dataType: 'json',
      data: function (term, page) {
        return {
          term: term
        };
      },
      results: function (data, page) {
        return { results: data };
      }
    }
  });
});

但是我坚持如何做到这一点,以便当管理员选择一个用户(也就是点击他们的下拉区域)时,页面重定向到JSON 数组中的 iduserview.php?id=1所在的位置。1

有兴趣的搜索功能:

public function searchUsers($term = '') {
    if (isset($term)) {
        $term = parent::secure($term);
        $params = array( ':searchQ' => $term . '%' );
        $sql = "SELECT distinct username as suggest, user_id, name
                FROM login_users
                WHERE username LIKE :searchQ
                OR name LIKE :searchQ
                OR user_id LIKE :searchQ
                ORDER BY username
                LIMIT 0, 5";

        $stmt = parent::query($sql, $params);

        if ( $stmt->rowCount() > 0 ) {
            while($suggest = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $data[] = array(
                    'id' => $suggest['user_id'],
                    'text' => $suggest['name'] . ' (' . $suggest['suggest'] . ')' . ' ID: ' . $suggest['user_id'],
                );
            }
        } else {
            $data[] = array('id'=>'0', 'text'=>'No results found!');
        }
        echo json_encode($data);
        flush();
    }
}
$searchParam = new Search();

if (isset($_GET['term'])) {
    // we secure the term before running the search and querying the database
    $term = $_GET['term'];
    switch (isset($_GET['sType']) ? $_GET['sType'] : NULL) {
        case 'users':
            $searchParam->searchUsers($term);
        break;
        case 'levels':
            $searchParam->searchLevels($term);
        break;
    }
}
4

2 回答 2

2

在发布此内容一年后遇到了同样的问题,并在谷歌上搜索了一些内容,最后在这里忘记了我曾经发布过它。

很好地找到了解决方案:

<script>
$(document).ready(function () {
    $("#search").select2({
        ajax: {
            url: "users.php",
            dataType: 'json',
            data: function (term) {
                return {
                    term: term,
                };
            },
            results: function (data) {
                return {results: data};
            }
        }
    });
    $("#search").on("select2-selecting", function(e) {
        window.location.href = 'user_edit.php?id=' +  e.val;
    });
});
</script>
于 2014-08-04T23:12:32.453 回答
2

版本 4.0 +

事件现在采用格式:select2:selecting(而不是 select2-selecting)

$("#search").on("select2:selecting", function(e) {
 window.location.href = 'user_edit.php?id=' +  e.val;
});
于 2020-02-04T09:48:46.677 回答