【问题标题】:Ajax autocomplete doesn't return correct valueAjax 自动完成不返回正确的值
【发布时间】:2016-05-07 09:59:57
【问题描述】:

我有一个 ajax 自动完成功能,它返回用户的全名。但是,当某些名称或值相同的情况下,它不会返回正确的值。相反,它返回下拉列表中的第一个值。即使它有 4 次相同的出现,它仍然返回第一个值。

当我点击史坦尼斯·艾林·拜拉席恩时,它会返回史坦尼斯·坦格利安·拜拉席恩。

这是我的 php 代码(sql/php 代码;ad.php):

<?php
include('config.php');
if($_POST)
{
    if($_POST['search_keyword'])
    {
        $similar = mysql_real_escape_string($_POST['search_keyword']);

        $result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");

        if (mysqli_num_rows($result) > 0) {
            while($row=mysqli_fetch_array($result))
            {
                //$name = $row['fullname'];
                //$copiedname = $row['fullname'];
                //$b_name= '<strong>'.$similar.'</strong>';
                //$final_name = str_ireplace($similar, $b_name, $name);
                ?>          
                <div class="show" align="left">
                    <span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
                    <span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span> 
                </div>


            <?php
            }
        }

        else {
            ?>
                <div class="show" align="left">
                    <span class="returnMessage">No matching records found.</span>
                </div>
            <?php
        }

    }



    mysqli_close($conn);
}
?>

HTML 输入表单:

<form method="post" action="try.php" name="try">
<div class='web'>
    <input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
    <input type="hidden" name="resID" id="resID"/>
    <div id="result"></div>
    <input type="submit" name="try" value="Submit">
</div>

AJAX/JS/JQUERY CODE(我认为这就是问题所在):

<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function() 
{ 
    var search_keyword_value = $(this).val();
    var dataString = 'search_keyword='+ search_keyword_value;
    if(search_keyword_value!='')
    {
        $.ajax({
            type: "POST",
            url: "ad.php",
            data: dataString,
            cache: false,
            success: function(html)
                {
                    $("#result").html(html).show();
                }
        });
    }
    return false;    
});

jQuery("#result").on("click", function(e)
    {
    /*var $clicked = $(e.target);
    var $name = $clicked.find('.returnName').html();    
    var decoded = $("<div/>").html($name).text();
    $('#search_keyword_id').val(decoded);

    var $clicked = $(e.target);
    var $id = $clicked.find('.returnID').html();    
    var id = $("<div/>").html($id).text();
    $('#resID').val(id);
     */
    $name = $('span.returnName',this).html(); 
    $name = $("<div/>").html($name).text().toString();
    $('#search_keyword_id').val($name);
    $id = $('span.returnID',this).html(); 
    $id = $("<div/>").html($id).text().toString();
    $('#resID').val($id);



});

jQuery(document).on("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search_keyword")){
    jQuery("#result").hide(); 
    }
});
});
</script>

即使我单击第二个或第三个或第四个值,它也确实返回第一个值。我的代码哪里出错了?请帮我。非常感谢!

【问题讨论】:

  • 您正在尝试重新发明轮子...似乎问题出在("#result").on("click" 方法上...检查一下:)
  • 我已经调查过了。但我似乎无法修复它......
  • 仅供测试;你可以用这个代码替换你的方法吗:jQuery("#result").on("click",".returnName" function(e) { $name = $(this).html(); $('#resID').val($name); });
  • 尝试了您的代码,它返回了实际的 div 代码... :(
  • 所以它返回的是点击跨度的html,对吧?..记住这是为了测试是否返回点击跨度的html...

标签: javascript php jquery ajax autocomplete


【解决方案1】:

您的代码当前正在收集#result 中类returnName 的所有元素,并且通过在该集合上调用.html() jQuery 将只返回找到的第一个元素的html。您的returnID 搜索也是如此。这就是为什么您只会得到第一个返回的条目。

修改您的#result 点击处理程序以仅触发具有类show 的元素,因为该元素将包含您的数据。

jQuery("#result").on("click", ".show", function(e){

然后您所要做的就是搜索具有类returnNamereturnID 的元素并调用.text()

var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);

大家一起来

jQuery("#result").on("click", ".show", function(e){
    var showName = $('.returnName',this).text();
    var showId = $('.returnID',this).text();
    $('#search_keyword_id').val(showName);
    $('#resID').val(showId);
});

尽管请注意,可能有更好的方法来返回数据并利用它,而不是在 html 元素中传输它。例如,使用 data-* attributes 而不是使用单独的 span 元素来包含您的 id。

另一种选择是使用jQuery-UI's autocomplete,它会为您完成大部分客户端工作,并从您的 php 脚本返回 JSON 格式的原始数据。

【讨论】:

  • 哇!!!!是的,.SHOW 包含数据。我认为不可能在... jQuery("#result").on("click", ".show", function(e) 中包含“.SHOW”。非常感谢。它解决了我的问题。谢谢!!!
【解决方案2】:

在你的 php 代码中,改变这个:

<div class="show" align="left">
      <span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
      <span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span> 
</div>

有了这个:

<div class="show" align="left">
    <span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>

还有你的新 jquery 函数:

jQuery("#result").on("click","'.returnName" function(e)
{
     var choosenName = $(this).html();    
     var choosenId = $(this).data('id');
     $('#search_keyword_id').val(choosenName );
     $('#resID').val(choosenId );
});

【讨论】:

  • 成功了!!!!这是与其他答案(也有效)不同的方法,但它有效。哇!!!太感谢了!!!谢谢你UUUU黑客!!!!
猜你喜欢
  • 2012-04-14
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2019-05-16
相关资源
最近更新 更多