如果有多个ID,会对Ajax响应做出反应

时间:2017-08-01 18:19:27

标签: php jquery html ajax

我收到带有动态ID的多个html元素的Ajax响应,我想对它们作出反应,就像用户点击它们一样。

$("#friend").keyup(function(){
        var friend = $(this).val();
        $("#friend_select").show();
        if(friend != ''){
            $('#friend_select').css("visibility", "visible");
            $('#friend').css("overflow", "visible");
            $.ajax({

                url: "../system/challenge_engine.php",
                method: "post",
                data:{friend:friend},
                dataType: "text",
                success:function(data)
                {
                    $('#friend_select').html(data);
                }
            });
        }else{
            $('#friend_select').html('');
            $('#friend_select').css("visibility", "hidden");

        }
    });

php代码:

<?php 
include_once("../includes/check_user.inc.php");
if($user_ok != true || $username == "") {
    exit();
}
$user = "";
$friend = $_POST["friend"];

$sql = "SELECT * FROM friends WHERE (user1 LIKE '%$friend%' AND user2 = '$username' AND accepted = '1') OR (user1 = '$username'  AND user2 LIKE '%$friend%' AND accepted = '1')";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
    while($row = mysqli_fetch_array($result)){
        if($row['user1'] == $username){
            $user .= '<p id="friend_'.$row['user2'].'" class="friend_name">'. $row['user2'].'</p>';
        }else{
            $user .= '<p id="friend_'.$row['user1'].'" class="friend_name">'. $row['user1'].'</p>';
        }
    }   
    echo $user;
}else{
     echo '<p>No result.</p>';
}

这里是其余的html代码:

<div class="select_friend">
    <label for="friend">Freund auswählen</label>
    <input id="friend" name="friend" class="friend" type="text" placeholder="Choose Friend...">
    <div id="friend_select" class="friend_select"></div>
</div>

我希望当用户点击下拉菜单的结果时,输入字段值应该更改为朋友的名称。我希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用jQuery中的.on方法。这是链接:http://api.jquery.com/on/

这样的事情:

$(&#39; .friend_name&#39;)。on(&#39;点击&#39;。function(){console.log($(this).text())})