2011-09-02 32 views
0

這是使用res.write我Node.js的功能:response.responseText增加了以前的responseText(node.js的,原型)

function: ping(){ 
    res.write(JSON.stringify({"datatype":"ping"})); 
    setTimeout(ping, 30000); 
} 

這是客戶端,要求寫在原型:

this.pushconnection = new Ajax.Request(pushserveraddress, { 
     method: 'get', 
     evalJSON: 'false', 
     onInteractive: this.pushconnectionInteractive.bind(this) 
    }); 
} 

pushconnectionInteractive: function(response) { 
} 

問題是response.responseText會隨着每個res.write的增加而增加。

實施例:

1st ping() received: response.responseText = {"datatype":"ping"} 

2nd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"} 

3rd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}{"datatype":"ping"} 

我不知道如果node.js的重新發送數據,或者,如果原型是存儲數據。我需要做的是response.responseText =不使用res.end();

+0

你忘了重新設置一個循環內迴應? –

+0

我認爲響應對象是爲每個onInteractive完全重新構建的。你能告訴我如何重置它嗎? – Brian

回答

0

你可能會調用不止一次this.pushconnection多發送的最後數據。

如果您將它自己的Ajax對象實例化爲this.pushconnection並繼續使用相同的ajax對象,那麼您的響應將會增長。

試試這個:

var ajax = this.pushconnection("example.com"); 
0

每個響應添加到以前的一個,獲得最後一個對象發送,如果ü使用PHP函數:

this.pushconnection = function (pushserveraddress) { 
    return new Ajax.Request(pushserveraddress, { 
    method: 'get', 
    evalJSON: 'false', 
    onInteractive: this.pushconnectionInteractive.bind(this) 
    }); 
} 

然後你可以這樣調用這個 (第1頁添加標題)

header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache'); 
header('connection: keep-alive'); 

(2發送數據)

function send_message($data_array) { 
echo json_encode($data_array).PHP_EOL; 
ob_flush(); 
flush(); 
在你的js

}

(原型):獲得最後的響應

new Ajax.Request(sUrl, { 
onInteractive:function(xhr){ 
var lastString = xhr.responseText.split("\n"); 
var lastObjectSent = lastString[lastString.length-2].evalJSON(); 
if(lastObjectSent.bValid){ 
    if(parseInt(lastObjectSent.bValid,10) === 1){ 
     this.status="finished"; 
     loadPage('done.php'); 
    }else{ 
     setNotification(oResult.sText,"Failure",5000); 
    } 
    }else if(lastObjectSent.progress){ 
    $('duplicatePassDates').down('.bar').setStyle('width:'+lastObjectSent.progress+'px'); 
} 
}, 
onSuccess:function(xhr){ 
if(this.status!=="finished"){ 
    this.onInteractive(xhr); 
} 
},