0

AJAXを使用して挿入し、取得して、取得後に追加する方法について、簡単なサンプルを作成しました<div>。しかし、テーブルのすべてのコンテンツを取得するのに問題があり、null値が返されます。

<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 に答える