response.responseText添加了之前的responseText(node.js,prototype)

时间:2011-09-02 18:53:47

标签: ajax node.js prototypejs

这是我使用res.write的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();的情况下发送最后一个数据

2 个答案:

答案 0 :(得分:0)

您可能不止一次致电this.pushconnection

如果您将this.pushconnection实例化为自己的Ajax对象并继续使用相同的ajax对象,那么您的响应将会增长。

请改为尝试:

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

然后你可以这样说:

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

答案 1 :(得分:0)

每个响应都添加到前一个响应,如果您使用该php函数,则获取最后一个对象: (第一个添加标题)

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(Prototype)中:获得最后的回复

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);
}
},