我有简单的php/ajax/mysql聊天。但不幸的是,当我将表单发送到数据库时,php 将空字符串发送到 MySQL,我该如何解决它?
这里页面.php代码,带有脚本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#messages").load('ajaxLoad.php');
$("#userArea").submit(function(){
$.post('ajaxPost.php', $('#userArea').serialize(), function(data){
$("#messages").append('<div>'+data+'</div>');
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div id="messages"></div>
<form method="post" action="ajaxPost.php" id="userArea" style="margin: 0 auto; font-size: 23px; text-align: center;">
<h1>Chat</h1>
<input type="text" name="message" />
<input type="submit" value="send!" />
</form>
</div>
<?php include_once('ajaxLoad.php'); ?>
<?php include_once('ajaxPost.php'); ?>
和 ajaxPost.php:
<?php
include_once('page.php');
include('config.php');
$message = $_POST['message'];
$db->Query("INSERT INTO messages(message1) VALUES ('$message')");
echo $message;
?>
如果您运行:alert($('#userArea').serialize())
它将向您显示您的消息。
去掉这些行:
<?php include_once('ajaxLoad.php'); ?>
<?php include_once('ajaxPost.php'); ?>
这些脚本只应该从 AJAX 使用,你不应该在只显示原始表单时执行它们。当你用include()
执行它们时,$_POST
中没有任何内容,所以你插入一条空消息。
您还没有显示ajaxLoad.php
中的内容,但是从您将其与$("#messages").load()
一起使用的方式来看,我怀疑它是否应该与include
一起运行。
我很确定当您使用 $.post()
调用它时ajaxPost.php
正常工作,并且空行来自include_once()
.
我认为它不应该阻止插入,但你也不应该有
include_once('page.php');
在ajaxPost.php
.