Php json_encode()没有将数据发送回AJAX调用

Php json_encode()没有将数据发送回AJAX调用,php,jquery,ajax,mysqli,Php,Jquery,Ajax,Mysqli,所以我尝试创建并实现一个实时搜索功能。这是我的PHP代码 <?php ini_set('display_errors', 1); error_reporting(~0); define('DB_USER', '*****'); define('DB_PASSWORD', '*****'); define('DB_SERVER', 'localhost'); define('DB_NAME', 'MUSIC'); if (!$db = new mysqli(DB_SERVER, DB_U

所以我尝试创建并实现一个实时搜索功能。这是我的PHP代码

<?php

ini_set('display_errors', 1);
error_reporting(~0);

define('DB_USER', '*****');
define('DB_PASSWORD', '*****');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'MUSIC');
if (!$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME)) {
    die($db->connect_errno.' - '.$db->connect_error);
}

$arr = array();
    $sql = "SELECT * FROM main WHERE titles LIKE '%%'";
    $result = $db->query($sql) or die($mysqli->error);
    if ($result->num_rows > 0) {
        while ($obj = $result->fetch_object()) {
            $arr[] = array('title' => $obj->titles);
        }
    }

echo json_encode($arr);
?>
我调用的脚本:

$document.readyfunction{ $'keyword'。在'input'上,函数{ var searchKeyword=$this.val; 如果searchKeyword.length>=3{ $.post'search.php',{keywords:searchKeyword},functiondata{ 警惕这里; $'ulcontent'。为空 $.eachdata,函数{ 在这里也是如此; $'ulcontent'。追加; }; },json; } }; }; 首先,永远不要使用或死亡,特别是在mysqli构造函数提示下:它永远不会是falsy

其次,如果遇到错误,您应该以外部使用者(如JS应用程序)能够理解错误发生的方式进行响应

第三,使用带有参数绑定的准备好的语句。这应该不言而喻

<?php

// these should really be set in your environment's php.ini
ini_set('display_errors', 'On');
error_reporting(E_ALL);

// set mysqli to throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $db = new mysqli('localhost', '*****', '*****', 'MUSIC');
    $stmt = $db->prepare("SELECT `id`, `titles` from `main` WHERE `titles` LIKE CONCAT('%', ?, '%')");
    $stmt->bind_param('s', $_POST['keywords']);
    $stmt->execute();
    $stmt->bind_result($id, $titles);

    $response = [];
    while($stmt->fetch()) {
        $response[] = ['id' => $id, 'title' => $titles];
    }
    $stmt->close();

    header('Content-type: application/json');
    echo json_encode($response);
    exit;
} catch (Exception $e) {
    http_response_code(500);
    echo $e;
}
当然,如果您的查询不包含任何结果,那么JS$。每个都不会迭代任何内容。您需要通过检查data.length在客户端处理这种情况


在我看来,您还应该尝试全文索引和匹配查询,而不是类似的查询。

请尝试console.logdata,而不是警报“Here”,然后检查控制台$sql=SELECT*FROM main WHERE title,如“%”;关键字在哪里?尝试设置普通的ajax调用并设置数据类型:“json”您检查过数据的值吗?你发现了什么?如果出现第一个警报,那么它显然返回了什么。@Justinas为什么,OP已经将预期的响应类型设置为json