首页 > 解决方案 > 具有自动完成功能的输入文本 - 未捕获的类型错误:$.ajax 不是 PHP、MySQL 和 jQuery 中的函数

问题描述

我正在尝试使用 PHP 和 MySQL 数据库中的用户信息在 jQuery 中进行自动完成文本输入。我收到以下错误:

Uncaught TypeError: $.ajax is not a function
at HTMLInputElement.<anonymous> (file.php:332)
at HTMLInputElement.dispatch (jquery-3.3.1.slim.min.js:2)
at HTMLInputElement.v.handle (jquery-3.3.1.slim.min.js:2)

我在所有页面中包含的 header.php 上导入 jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

这是我的 file.php,它是包含脚本和输入的文件,我将只留下一部分代码,当然输入在表单中

<input type="text" name="autor" id="autor" placeholder="Escreve o nome do autor" />
<div id="autorLista"></div>

<script>
    $(document).ready(function() {
        $('#autor').keyup(function() {
            var query = $(this).val();;
            console.log(query);

            if (query != '') {
                $.ajax({
                    url: "./components/search.php",
                    method: "POST",
                    data: {
                        query: query
                    },
                    success: function(data) {
                        $('#autorLista').fadeIn();
                        $('#autorLista').html(data);
                    }
                });
            }
        });

        $(document).on('click', 'li', function() {
            $('#autor').val($(this).text());
            $('#autorLista').fadeOut();
        });
    });
</script>

我什至不知道 php 代码是否正常工作,但我认为是。我将它留在下面(search.php):

<?php

if (isset($_POST['query'])) {
    $link = new_db_connection();
    $stmt = mysqli_stmt_init($link);

    $output = '';

    $query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE ?";

    if (mysqli_stmt_prepare($stmt, $query)) {
        $output = "<ul>";

        if (mysqli_stmt_num_rows($stmt) > 0) {
            mysqli_stmt_bind_param($stmt, 's', $nome_user);

            mysqli_stmt_execute($stmt);

            mysqli_stmt_bind_result($stmt, $id_user, $nome_user);

            if (mysqli_stmt_fetch($stmt)) {
                $output .= "<li>" . $nome_user . "</li>";
            }
        } else {
            $output = '<li>O utilizador que procura não existe.</li>';
        }
        $output .= "</ul>";
        echo $output;
    } else {
        echo 'erro';
    }
}

我已经尝试过更改 jquery 的版本,检查了苗条版本等,但没有什么可以使这项工作......有什么想法吗?有任何疑问或者如果我不清楚,请告诉我。谢谢!

标签: phpjquerymysqlajax

解决方案


在您的错误中,它显示您正在使用没有 Ajax 的 jQuery slim。

(jquery-3.3.1.slim.min.js:2)

请检查您使用的是仅普通的 jQuery,而不是苗条版本。


推荐阅读