jquery $.ajax request remains pending

后端 未结 2 503
臣服心动
臣服心动 2021-01-17 04:49

I have made a simple chat application which uses long-polling approach using jquery,

function sendchat(){ 
// this code sends the message
$.ajax({
  url: \"s         


        
相关标签:
2条回答
  • 2021-01-17 05:02

    The issue was because of session locking;

    both send.php and listen.php files use session variables, so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).

    0 讨论(0)
  • 2021-01-17 05:23

    How do I implement basic "Long Polling"?

    the link above is a similar question that may help you.

    it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...

    you do not need to do send.php and listen.php, because you can do it simply on one page both of them.

    function check(){
    $.ajax({
      url  : 'process.php',
      data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
      type : 'post',
      success: function (r){
        if(r.message){
           $('#result').append(r.message);
           check();//can use a setTimeout here if you wish
        }
      }
    });
    }
    

    process.php

    <?php 
    
    $msg = $_POST['msg'];//is blabla in this case.
    $arg['message'] = $msg;//or grab from db or file
    //obviously you will have to put it on a database or on a file ... your choice
    //so you can differentiate who sent what to whom.
    echo json_encode($arg);
    
    ?>
    

    obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.

    I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.

    however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel

    0 讨论(0)
提交回复
热议问题