最佳实践,如何使用jQuery创建一个简单的php聊天的ajax请求?

问题描述:

i have a simple chat and the way i do thinks now is like this:

function ajax() { 
    $.ajax({  
        url: '/chat/index/json',
        type: 'POST',
        dataType: "json",
        success: function(data) {   
           // output the html to my chat window
        }
    });
    window.setTimeout("ajax()",5000);
}


$(document).ready(function() {
    ajax();
    $('#chat').submit(function(e) { 
        e.preventDefault();
        sendMessage();
    });
});


function sendMessage()
{   
    // grab the values from text textarea
    $.ajax({
          url: '/chat/index/jsave',
          type: 'POST',
          dataType: "html",
          data: message,
          success: function(d) {  
              // empty the textarea 
              ajax(); 
          }
    });
}

i basically call the ajax(); function every 5 seconds. Im not sure if this is the best way to do this because i have a request to the server every 5 sec.

is there a better way of doing this?

thanks

我有一个简单的聊天,我现在想的方式是这样的: p>

  function ajax(){
 $ .ajax({
 url:'/ chat / index / json',
 type:'POST',
 dataType:“json”,
成功 :function(data){
 //将html输出到我的聊天窗口
} 
}); 
 window.setTimeout(“ajax()”,5000); 
} 
 
 
 $  (document).ready(function(){
 ajax(); 
 $('#chat')。submit(function(e){
 e.preventDefault(); 
 sendMessage(); 
}  ); 
 
 
; 
 
 
 
函数sendMessage()
 {
 //从文本textarea中获取值
 $ .ajax({
 url:'/ chat / index / jsave',\  n类型:'POST',
 dataType:“html”,
 data:message,
 success:function(d){
 //清空textarea 
 ajax(); 
} 
})  ; 
} 
  code>  pre> 
 
 

我基本上每隔5秒调用 ajax(); code>函数。 我不确定这是否是最好的方法,因为我每隔5秒向服务器发出一次请求。 p>

有更好的方法吗? p>

谢谢 p> div>

First of all, try to use GET instead of POST. GET will work faster and as you don't send security protected data you can use it. If you have chat...you must have a request to server every n seconds.
Why GET method is faster than POST?