0

我做了一个简单的示例,说明如何使用 AJAX 插入并检索它,然后在获取它后将其附加到一个中<div>。但是我在获取表的所有内容时遇到了麻烦,它返回了一个空值。

<div id="wrap-body">
  <form action method="post">
    <input type="text" name="username" id="username">
    <input type="text" name="msg" id="msg">
    <input type="button" id="submit" value="Send">
  </form>
  <div id="info">
  </div>
</div>

jQuery:

<script>
    $(document).ready(function (){
        $('#submit').click(function (){
            var username = $('#username').val();
            var msg = $('#msg').val();

            $.ajax({
                type: 'POST',
                url: 'get.php',
                dataType: 'json',
                data:'username='+username+'&msg='+msg,
                success: function (data){
                    $('#info').append("<p> you are:"+data.username+"</p> <p> your message  is:"+data.mesg);
                }
            });
        });
    });
</script>

PHP:

<?php 
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';

$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);

$username = $_POST['username'];
$msg = $_POST['msg'];

$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";

if(@!mysql_query($insert)){
    die('error insertion'.mysql_error());
}

$get = "SELECT * FROM info ";

$result=mysql_query($get)or die(mysql_error());

while ($row = mysql_fetch_array($result))
{
    $return  = $row['user_name'];
    $return = $row['message'];
}
echo json_encode($return);
?>
4

2 回答 2

2

您的 while 应该创建数组,然后执行 json_encode

试试下面的代码

$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
   'username'=>$row['user_name'],
   'mesg'=>$row['message']
);
}

echo json_encode($data);
exit

现在编写您的 javascript 成功处理程序,如下所示

$.ajax({
                type: 'POST',
                url: 'get.php',
                dataType: 'json',
                data:'username='+username+'&msg='+msg,
                success: function (data){
                   $.each(data, function(i, item) {
                     $('#info').append("<p> you are:"+data[i].username+"</p> <p> your message  is:"+data[i].mesg);
                   });​

                }
            });
于 2012-09-24T18:10:24.820 回答
0

您必须解决几个问题,但您必须从返回与 ajax 调用所期望的类型相同的类型开始:

$return = array()
if ($row = mysql_fetch_array($result))
{
  $return['username']  = $row['user_name'];     
  $return['mesg'] = $row['message'];

}

echo json_encode($return);
于 2012-09-24T18:11:45.990 回答