通过 AJAX 调用 PHP 文件,将 $_GET 变量传递到 MySQL 查询中,然后回显到响应中


Calling PHP file via AJAX, passing $_GET variable into MySQL query, then echoing into response

所以我有这个jQuery AJAX调用,当我单击任何带有class="username"属性的div时激活,该属性包含用户的用户名,例如:

<div class="username">Sneaky</div>

下面是 jQuery AJAX 调用:

var usersName = '';
$('#chatContainer').delegate('div.username', 'click', function(e) {
    usersName = $(this).text();
    $.ajax({
        method: 'GET',
        url: 'profile_popup.php',
        data: { usersName: usersName },
        success: function(data) {
            $("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(data);
        }
    });
});

这是它调用的 PHP 文件:

include 'MySQL_connect.php';
$name = mysql_real_escape_string($_GET['usersName']);
$sql = "SELECT chat_color FROM users WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row["chat_color"];
$sql = "SELECT profile_pic FROM profiles WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$profilePic = $row["profile_pic"];
echo "<div style='color:$chatColor'>$name</div>
        <img style='height:64px' src='../profile/profile_pictures/$profilePic'>";

我的问题是它返回没有错误但没有 MySQL 数据库值,如下所示:

<div id="profilePopup">
     <div style="color:"> Sneaky</div>
     <img src="../profile/profile_pictures/" style="height:64px">
</div>

关于为什么这没有按预期工作的任何线索?我在这个网站上用jQuery,PHP和MySQL做了很多工作,这似乎应该可以正常工作。

如果我

错了,不要咬我,假设你所有的SQL代码都是正确的,你能试试吗

echo "<div style='color:" . $chatColor . "'>" . $name . "</div>
    <img style='height:64px' src='../profile/profile_pictures/" .     $profilePic . "'>";

--编辑--也许将您的 PHP 文件编辑为:

include 'MySQL_connect.php';
$name = $mysqli->real_escape_string($_GET['usersName']);
$sql = "SELECT `chat_color`, `profile_pic` FROM users LEFT JOIN profiles ON (`users`.`username` = `profiles`.`username`) WHERE `username` = '" . $name . "'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row['chat_color'];
$profilePic = $row['profile_pic'];
echo "<div style='color:$chatColor'>$name</div>
    <img style='height:64px' src='../profile/profile_pictures/$profilePic'>";

我想通了。我做了一些测试,在检查了javascript"usersName"变量的设置后,我注意到开头有一个空格。我不知道为什么,也不知道它是如何到达那里的,但它就在那里。我只是在PHP文件中做了一个快速解决方法,如下所示:

$name = mysql_real_escape_string($_GET['usersName']);
$name = ltrim($name," ");

这只是从字符串开头修剪空格。感谢所有的帮助!:)

试试这个。

.PHP

$text='<div style="color:'.$chatColor.'">'.$name.'</div>
<img style="height:64px"src="../profile/profile_pictures/'.$profilePic .'">';
echo '{"item" :'.json_encode($text).'}';

阿贾克斯

success: function(data) {
    obj=$.parseJSON(data);
    $("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(obj.item);
}