实时 AJAX 搜索手机号码

Live AJAX search mobile numbers

我正在制作一个网络应用程序。主索引页面有一个用于搜索的大输入标签。一个人输入一个手机号码,然后通过 AJAX 和 php,我对 MySQL 数据库进行了实时搜索。

我能够从数据库中检索所需的行。我试图在结果数组上执行 print_r() ,它出现了。但是当我尝试只使用数组的一个元素时,它不会。

请看能不能找到问题所在:

Javascript

<script>
$(document).ready(function(e) {
    $('#search').keyup(function(e) {
                if($(this).val().length > 2){
        $.get('php/search.php', {input: $(this).val()}, function(data){
                        alert(data);
                        });
                }
    });
});
</script>

php/search.php 文件是:

<?php
require_once 'customer.php';

$input = $_REQUEST['input'];
print_r($cus->read($input));
?>

而customer.php文件是:

public function read($input) {
    //What search needs to do
    //Part 1 - Check if input is a mobile number or Text
    if(is_numeric($input) && strlen($input) > 2){
       //Search in mobile number
       $sql = "SELECT * FROM customers WHERE mobile LIKE '{$input}%' LIMIT 1";
       $result = $this->query($sql);
       $output = json_encode(mysqli_fetch_assoc($result));
       return $output;
    }else{}
}

$cus = new Customer();

如果我删除 search.php 中的 print_r 函数并在 javascript 中更改

alert(data);

alert(data[0]);

我收到一个提示 "undefined"。

奇怪的是,如果我更改为

alert(data[id]);

没有任何反应。但如果我改为

alert(data[name]);

我又变得不确定了。

试试这个

$(function() {
  $('#search').keyup(function(e) {
    var val = $(this).val();
    if (val.length > 2) {
      $.get('php/search.php', {
        input: val
      }, function(data) {
        var res = $.parseJSON(data);
        if (res) alert(res["name"]);
      });
    }
  });
});