与jQuery AJAX聊天

I have two python scripts (provided by my instructor).

  • getchat.py takes no params and it returns all messages in JSON a table of objects that contains date, time , user and the message .
  • sendchat.py which takes a message and returns in JSON an object with two fields num that can be either 1,0 for : the message is empty or it was successfully added respectively .

What I want to do is when a user tries to send a message it use sendchat.py to post the msg in the database and use getchat.py afterwards to get all messages and show them.

<div id="chatmsg"></div>
<div id="cwrapper">
    <input class="msg" type="text" id="msg" name="msg">
    <button id="send">Send</button>
</div>

My jQuery script so far (I used some functions that were used documentation just to try)

$("button").click(function() {
    $.getJSON('./getchat.py', function(data){
        var items = [];
        $.each(data, function(d) {
            items.push("<li>" + d + "</li>");
        });

        $("<ul/>", {
            html: items.join( "" )
        }).appendTo("#chatmsg");
    });

    $.post("./sendchat.py", { msg: $("#msg").val() }, function(data, status) {
        // I don't know how to deal with this.
    });
});

All I get is a list 0,1,2,... each time that I press send. The list appears for half a second and disappears. Where did I go wrong? How can I implement this properly? Thank you all!

Use ready to get the chats

$( document ).ready(function() {
       $.getJSON('./getchat.py', function(data){
        var items = [];
        $.each(data, function(d) {
            items.push("<li>" + d + "</li>");
        });

        $("<ul/>", {
            html: items.join( "" )
        }).appendTo("#chatmsg");
    });
    });


// this is to post a message
$("button").click(function() {
    
    $.post("./sendchat.py", { msg: $("#msg").val() }, function(data, status) {
        // I don't know how to deal with this.
// Get the messages, better if only get the last
$.getJSON('./getchat.py', function(data){
        var items = [];
        $.each(data, function(d) {
            items.push("<li>" + d + "</li>");
        });

        $("<ul/>", {
            html: items.join( "" )
        }).appendTo("#chatmsg");
    });


    });
});

I don't try this code, but you can be an idea

</div>

$.getJSON('./getchat.py', function(data){



      //First show the data on your browser inspector NOT EMPTY
    console.log(data);
       
      //Later you need parse JSON
      var j = JSON.parse(data);

  //See in inspector
  console.log(j);

  //you can display your object and fields
// For example    j.message or j[0].message

// A for o foreach like you preffer, something like this

        var items = [];
        $.each(data, function(d) {
            items.push("<li>" + d + "</li>");
        });

        $("<ul/>", {
            html: items.join( "" )
        }).appendTo("#chatmsg");
    });

</div>