且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL中插入新行时,如何编写Ajax代码以获取新行?

更新时间:2023-12-04 14:06:29

最近,我正在研究这种聊天模块,我可以在您的代码中说些更正

Recently I have worked on a chat module of this kind and I can say some correction in you code

首先不要以您使用的方式使用 setInterval

First of all don't use setInterval in the way you are using ,

为什么

因为在您的特定代码中,请求每2秒发送到服务器一次,所以如果网络速度较慢,您的代码将倾向于向服务器发送大量请求,并且这些请求之间的协调将很困难.

because in your particular code the request is send to the server every 2 second , so if the network is slow your code will have the tendency to send to much request to the server and coordination between those request would be difficult.

所以你要做的是

function getNewMessage(){

            $.ajax ({
                     type: "POST",
                     url: "chat.php",
                     data: { destination_hashed1: destination_hashed },

                     success: function(data) {
                            $("#messages").html(data);
                     },
                     complete : function(){  // this will be called even if our request fail, success etc
                         setTimeout(function(){   // send request after 2 second from the complition of the previous request
                             getNewMessage();       
                         },2000);
                     }
             });

}

解析ajax调用的聊天结果有两种方法

There are two approach in parsing the chat result from the ajax call

a)从ajax调用中获取html(如果您将来要扩展模块,这将很慢且效率低下)

a) get the html from the ajax call (this would be slow and inefficient in case you want to extend your module in the future)

您可以简单地从succes参数的ajax调用中获取html内容,可以将其附加到表中

You can simpley get the html content from the ajax call on succes parameter you can append that to the table

 For example : -

   if the response from the server on new message is 

     <div class="chat"> 
       <lable>John</lable>
         Hi there !!!
    </div>

然后解析内容将是这样

             success: function(data) {
                    // $("#messages").html(data);   //this will change the content in every request
                    $("#messages").append(data);   // this will append the new conent
             },

b)另一个方法是获取json格式的数据(更好的方法)

b) Well the other approch would be to get data in json format(a lot better approch )

例如:-

   if the response from the server on new message is 

     { 
       username : 'john',
       message  : 'Hi there !!!'
     }

然后解析内容将是这样

             success: function(data) {
                    // $("#messages").html(data);  this will change the content in every request
                    $("#messages").append('<div class="chat">'+
                                            '<lable>'+data.username+'</lable>'+
                                              data.message +
                                          '</div>');    this will append the new conent
             },