onreadystagechange只调用一次(socket和ajax)

时间:2017-03-20 14:24:24

标签: ajax sockets

我正在尝试使用socket进行ajax。我发现我的服务器程序可以接收从客户端发送的数据,并且收到的xml文件是正确的。但是,onreadystage回调函数只被调用一次(当readyState = 1时)。我做错了吗? 以下是与ajax相关的函数:

function requestAjax(){
        var msg=document.getElementById("msgToSocket").value;           
        var xhr=false;
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
            xhr.overrideMimeType("text/xml");
        }
        else if(window.ActiveXObject)
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
        if(xhr){
            xhr.open("GET", "socketSample1Ajax.php?msg="+msg+"&count="+(++ajaxCount), true);
            xhr.onreadystagechange=sendMsgToAjax(xhr);
            xhr.send(null);
        }

    }

function sendMsgToAjax(xhr){
        if(xhr.readyState==4 && xhr.status==200){
            var xmlDoc=xhr.responseXML;
            var read=xmlDoc.getElementsByTagName("read")[0].firstChild.nodeValue;
            var write=xmlDoc.getElementsByTagName("write")[0].firstChild.nodeValue;
            document.getElementById("readParagraph").innerHTML=read;
            document.getElementById("writeParagraph").innerHTML=write;
        }
    }

和我的ajax充当socket的客户端:

if(isset($_GET["msg"])){
    $msg=$_GET["msg"];
    if(!socket_write($socket, $msg))
        $resultWrite="Write failed";
    else
        $resultWrite="Written";
}
else{
    socket_write($socket, "No data input");
    $resultWrite="No data written";
}
$buffer=socket_read($socket, 1024, PHP_BINARY_READ)or die(socket_last_error($socket)."\n");
if(!$buffer)
    $resultRead="No data";
else
    $resultRead="Buffer Data: ".$buffer;
socket_close($socket);

感谢您的帮助!

0 个答案:

没有答案