我正在尝试使用ajax和php json创建一个用户搜索系统,例如facebook。但是我有一个问题。

在数据用户表中有Marc ZuckerbergMarc ZeynMarc Alp。我的意思是3用户的名字是相同的,因此通常在我写Marc名称时,我应该从数据中获取所有Marc名称。喜欢

<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>


但我并没有获得所有马克的名字,只是我得到了一个马克的结果。 Chrome开发者控制台向我显示所有Marc名称,但不在HTML中显示我的名字。我认为我需要一些来自Ajax成功的代码。

JS

$('body').delegate('#searchkey','keyup', function(){
      clearTimeout(timer);
      timer = setTimeout(function(){
          var box = $('#searchkey').val();
          contentbox = $.trim(box);
          var dataString = 'keys=' + contentbox;
          if(contentbox !==''){
            $.ajax({
              type: "POST",
              url: siteurl +"requests/search.php",
              data: dataString,
              dataType:"json",
              cache: false,
              beforeSend: function(){},
              success: function(data){
                   $('.un').html(data.username);
                   $('.uf').html(data.fullname);
              }
            });
          }
      });
   });


search.php

<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
     $keys = mysqli_real_escape_string($db, $_POST['keys']);
    $keyRestuls = $WidGet->SearchUser($keys);
    if($keyRestuls) {
        // If array is in data
     foreach($keyRestuls as $datas) {
        $dataUsername = $datas['username'];
        $dataUserID = $datas['fullname'];
        $data = array(
          'username' => $dataUsername,
          'fullname' => $dataUserID
        );
       echo json_encode( $data );
 }
}
}
?>


SearchUser函数在这里

    public function SearchUser($keys){
       $keys = mysqli_real_escape_string($this->db, $keys);
       $result = mysqli_query($this->db,"SELECT
          username,
          uid,
          fullname FROM
          users WHERE
          username like '%{$keys}%' or fullname like '%{$keys}%'
          ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
             while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
                 $data[]=$row;
             }
             if(!empty($data)) {
             // Store the result into array
              return $data;
             }
      }

最佳答案

您的PHP脚本正在生成格式错误的JSON

{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}


它应该产生

[
    {"username":"marc1","fullname":"Marc Zuckerberg"},
    {"username":"marc3","fullname":"Marc Zeyn"},
    {"username":"marc2","fullname":"Marc Alp"},
]


您可以通过附加到数组中来解决问题,而不是独立地写每行

foreach($keyRestuls as $datas)
{
    $dataUsername = $datas['username'];
    $dataUserID = $datas['fullname'];
    $data[] = array(
      'username' => $dataUsername,
      'fullname' => $dataUserID
    );
}
echo json_encode( $data );


然后,您必须在JS中循环遍历$data,建议您使用$.each

function success(data) {
    $.each(data, function(key, value) {
        console.log(value.username + ": " + value.fullname);
    })
}

10-05 23:58