【问题标题】:Combinging a PHP script with another PHP file, jQuery and HTML将 PHP 脚本与另一个 PHP 文件、jQuery 和 HTML 相结合
【发布时间】:2011-06-02 01:16:48
【问题描述】:

我有一个 PHP 搜索建议脚本,它使用 MySQL 数据库作为其后端,并使用 jQuery 将内容推送到搜索框页面。 PHP 目前在Suggest.php 中,我的搜索框在index.php 中。我想将来自Suggest.php 的PHP 脚本放入index.php 脚本代码中,但它似乎不起作用。为什么会这样?

这是我的Suggest.php代码:

<?php

$database=new mysqli('localhost','username','password','database');

if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
            if(strlen($query)>0){
                $suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
                if($suggestions){
                    echo '<ul id="suggest">';
                    while($result=$suggestions->fetch_object()){
                        echo '<li>'.$result->name.'</li>';                      
                    }
                    echo '</ul>';
                }
            }
        }
?>

这是我的 index.php 代码:

<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>function lookup(a){if (a.length==0){$("#suggestions").hide();} else {$.post("suggest.php",{query:"" + a + ""},function (b){$("#suggestions").html(b).show();})}};</script>

<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>
<div id='suggestions'></div>
</form>

【问题讨论】:

    标签: php jquery mysql html


    【解决方案1】:

    看起来 index.php 创建了您的用户使用的界面,但Suggest.php 返回了查找建议。当您尝试获取查找建议时,您不希望界面的另一个副本返回,因此您不能调用 index.php 代替Suggest.php

    此外,index.php 并不是真正的 php 文件,至少从您发布的内容来看是这样。也可以是 index.html

    【讨论】:

      【解决方案2】:

      一旦一个 PHP 页面被发送出去,如果@bbg 说的是真的,那么在没有刷新页面的情况下就无法在其中实现任何进一步的 PHP 代码。我建议您使用 AJAX,它可以发送请求以获取在 index.php 上执行的Suggest.php 脚本。我还建议您将代码放在函数中的Suggest.php(我认为它们使代码更漂亮)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多