从PHP实现MaterialiseJS自动完成?

时间:2017-03-21 22:17:54

标签: javascript php jquery

我的PHP:

    <?php
require_once __DIR__ . '/../inc/_puredb.php';
$query = $db->prepare("SELECT user_name FROM users");
$query->execute();
if($query->rowCount() > 0) {
    $rows = array();
    while($res = $query->fetchObject()) {
        array_push($rows, array($res->user_name => '/img/users/' . $res->user_name . '/avatar.png'));
    }
    echo json_encode($rows);
} else
    echo "";
?>

我的JS:

$.ajax({
    url: "/ajax/PermissionAutocomplete.php",
}).done(function(resJson) {
    if(resJson !== "") {
        //var resJson = JSON.parse(resJson); <- this is commented to try if it worked better without it
        $('input.mauto').autocomplete({
            data: resJson,
            limit: 10,
        });
    }
});

任何想法为何不起作用?我正在使用Materialise:http://materializecss.com/forms.html#autocomplete

PHP输出:

[{"User1":"\/img\/users\/User1\/avatar.png"},{"User2":"\/img\/users\/User2\/avatar.png"}]

1 个答案:

答案 0 :(得分:2)

您需要将 resJson变量从对象数组转换为对象。 从:

[{"User1":"\/img\/users\/User1\/avatar.png"},{"User2":"\/img\/users\/User2\/avatar.png"}]

为:

{"User1":"/img/users/User1/avatar.png","User2":"/img/users/User2/avatar.png"}

为了实现这一目标,您可以使用arr.reduce(callback, [initialValue])

摘录:

$(function () {
  var resJson = [{"User1":"\/img\/users\/User1\/avatar.png"},{"User2":"\/img\/users\/User2\/avatar.png"}];
  $('input.autocomplete').autocomplete({
      data: resJson.reduce(function(obj, item){
          var key = Object.keys(item)[0];
          obj[key] = item[key];
          return obj;
      },{}),
      limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
  });

});
/* fallback */
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: local('Material Icons'), local('MaterialIcons-Regular'), url(http://fonts.gstatic.com/s/materialicons/v21/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  -webkit-font-feature-settings: 'liga';
  -webkit-font-smoothing: antialiased;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script>


<div class="row">
    <div class="col s12">
        <div class="row">
            <div class="input-field col s12">
                <i class="material-icons prefix">textsms</i>
                <input type="text" id="autocomplete-input" class="autocomplete">
                <label for="autocomplete-input">Autocomplete</label>
            </div>
        </div>
    </div>
</div>