Ajax 数据嵌入页面,而不是返回正确的结果

Ajax data embedding page instead of returning proper results

本文关键字:返回 结果 数据 Ajax      更新时间:2023-09-26

我有一个简单的搜索区域,它使用JavaScript在用户键入时显示相关的搜索结果。以下是它的代码:

<div class="message_content">
    <input type="text" id="user_search" class="form-control search_box" placeholder="Search for people">
    <div id="search_results">
        <span class="no-result" style="line-height: 38px;">Enter your query</span>
    </div>
</div>

以下是lib.js中的 JS:

$("input#user_search").keyup(function() {
    var elt = $("input#user_search").val();
    $curr = $(this);
    $.ajax({
        url : "u.search.php",
        type: "GET",
        data : {val: elt},
        success:function(data, textStatus, jqXHR)
        {
            if (data.length) {
                $("div#search_results").html(data);
            }
            else $("div#search_results").html('<span class='"no-result'">Enter your query</span>');
        },
        error: function(jqXHR, textStatus, errorThrown){}
    });
});

最后,以下是u.search.php的代码:

<?php
$search = strtolower(htmlspecialchars($_GET['val']));
if (strlen($search) < 1);else {
    // Run query on the DB
    ...
    print "<div id='"search-list'" class='"list-group'">";
    // populate results
    while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
    {
        // variable declarations
        print "<a href='"#'" id='"$result'" class='"list-group-item'">";
        print     "<img src='"$pic'">";
        print     "<span>$name</span>";
        print "</a>";
    }
    print "</div>";
}
?>

这里的问题是,如果我在文本框、index.php页面(搜索框所在的页面)中键入任何内容,div#search_results的 html 将变为index.php .如果我在 ajax success 函数中console.log(data),控制台会显示 index.php 页面的代码(不是实际的源代码,而是您可以在浏览器的页面源代码中看到的代码)。

div#search_results基本上有索引.php嵌入其中。我尝试对 PHP 后端代码进行更改,但结果中没有反映任何更改。这是怎么回事?

您正在使用查询字符串来获取搜索变量。但是你没有发送任何东西。 因此,更改搜索.php使用 POST 或更改 ajax 方法来发送查询字符串...

$.ajax({
        url : "u.search.php?val=" + encodeURIComponent(elt),
        type: "GET",
        success:function(data, textStatus, jqXHR)
        {
            if (data.length) {
                $("div#search_results").html(data);
            }
            else $("div#search_results").html('<span class='"no-result'">Enter your query</span>');
        },
        error: function(jqXHR, textStatus, errorThrown){}
    });