gpt4 book ai didi

php - 键入时实时搜索结果...我这样做是否正确? jQuery + PHP

转载 作者:搜寻专家 更新时间:2023-10-31 21:46:34 26 4
gpt4 key购买 nike

我有一个搜索输入和一个隐藏的 div。当您开始在搜索输入中键入内容时,隐藏的 div 将变为可见并显示结果。在本例中,我正在搜索客户名称。

一切正常,但我认为我的代码可以做得更好,但我不确定从哪里开始。每个 keyup 请求一个 PHP 脚本,该脚本访问数据库中的表以查找类似的字符串。但是在我的 PHP 脚本中,我回显了一些我不确定的 JS/jQuery 是好的做法。下面是我的代码。我是以正确的方式解决这个问题还是我完全偏离了基地?有什么改进建议吗?

Javascript

$("#search").keyup(function() {
$("#search_results").show("fast");
$.ajax
({
type: "POST",
url: "http://localhost:8888/index.php/welcome/search/" + $("#search").val(),
success: function(html)
{
$("#search_results").html(html);
}
});
});

PHP

function search($search_string = false)
{
if ($search_string)
{
$this->db->like('name', $search_string);
$query = $this->db->get('clients');

if ($query->num_rows() == 0)
{
echo "No client exists.";
}
else
{
foreach ($query->result() as $row)
{
echo '<script>';
echo '
$("#client_results_'.$row->id.'").hide();
$("#'.$row->id.'").toggle(function()
{
$.ajax
({
type: "POST",
url: "http://localhost:8888/index.php/welcome/search_client_ads/" + '.$row->id.',
success: function(html)
{
$("#client_results_'.$row->id.'").html(html).show("fast");
}
});
}, function()
{
$("#client_results_'.$row->id.'").hide("fast").html("");
});';
echo '</script>';
echo '<p><span id="'.$row->id.'">'.$row->name.'</span></p>';
echo '<div id="client_results_'.$row->id.'"></div>';
}
}
}
else
{
echo '';
}
}

function search_client_ads($client_id)
{
$query = $this->db->get_where('online_ads', array('client' => $client_id));

if ($query->num_rows() == 0)
{
echo "No ads exist.";
}
else
{
foreach ($query->result() as $row)
{
echo $row->id;
}
}
}

最佳答案

与其返回大量脚本,不如尝试返回一个 json 字符串并让 jquery 循环遍历它。

关于php - 键入时实时搜索结果...我这样做是否正确? jQuery + PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com