我尝试编写此代码并遇到麻烦说 警告:第 15 行 E:\xampp\htdocs mpi\get_chat_interface.php 中未定义的数组键“user_name”
这是我的 php 代码`
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$recipientUsername = $_POST['user_name'];
$stmt = $pdo->prepare("SELECT message FROM messages WHERE sender = ? OR receiver = ?");
$stmt->execute([$recipientUsername, $recipientUsername]);
echo "<div class='live-chat-name'><p>$recipientUsername</p></div>";
echo "<div class='chat-content'>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$message = $row['message'];
echo "<p>$message</p>";
}
echo "</div>";
echo "<div class='chat-input'>";
echo "<form id='chatForm'>";
echo "<input type='text' id='messageInput' placeholder='Send Message...' required>";
echo "<input type='hidden' id='recipientUsername' value='$recipientUsername'>";
echo "<button type='submit'>Send</button>";
echo "</form>";
echo "</div>";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
这是 JS
function loadChatInterface(user_name) {
// AJAX request to load the chat interface for a specific user
$.ajax({
url: 'get_chat_interface.php',
method: 'POST',
data: { user_name: user_name }, // Use the correct key here
success: function (data) {
$('#chatInterface').html(data);
}
});
}
你忘了添加数据的contentType
contentType: "application/x-www-form-urlencoded;
,你的请求应该是这样的:
function loadChatInterface(user_name) {
// AJAX request to load the chat interface for a specific user
$.ajax({
url: 'get_chat_interface.php',
method: 'POST',
data: { user_name: user_name }, // Use the correct key here
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
$('#chatInterface').html(data);
}
});
}