如何使用ajax调用提交页面?

时间:2014-06-10 06:44:26

标签: php ajax

我想使用ajax在php中创建一个聊天室。因此,我想通过点击提交来调用另一个页面。我有两页chat.php和getchat.php。我哪里错了,如何调用getchat.php。我试过但功能不起作用。请帮帮我。

chat.php

    <script>
    function showUser() {

      xmlhttp.open("GET","getchat.php",true);
      xmlhttp.send();
    }
    </script>
<form onSubmit="showUser(this.value)" method="post">
<label>Name :</label>
<input type="text" name="username" /><br />
<textarea name="message"></textarea>
<input type="submit" name="submit" />
</form>

getchat.php

<?php
$con = mysqli_connect('localhost','root','','ajax');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");

$sql="SELECT * FROM chat";
$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>Name</th>
<th>Message</th>

</tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['message'] . "</td>";
  echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:2)

我做了类似这样的事情

chat.php

<form id="chat_form" method="post">
<label>Name :</label>
<input type="text" name="username" /><br />
<textarea name="message"></textarea>
<input type="submit" name="submit" />
</form>
<div id="result"></div>

<script src="jquery-2.1.0.js"></script> 
<script>    
$(document).ready(function() {

    $('#chat_form').submit(function(e){
        e.preventDefault();
        var data = $("#chat_form").serializeArray();

        $.ajax({
            url: 'getchat.php',
            type: "post",
            data: data,
            success: function(info){
                $("#result").html(info);
            },
            error:function(){
                $("#result").html('there is error while submit');
            }   

        }); 
    });
});
</script>

getchat.php

没有改变你的