我在textarea id="save"
内保存addEventListener
的值。然后,我使用xhr
将其发送到服务器,同时我使用Google App Engine渠道API打开频道,然后我尝试捕获使用onMessage
发回的消息。
一切正常,但返回的消息除外。我知道返回的消息将是evt.data
,但不会记录。你能帮我理解我做错了什么吗?这是我previous question的后续跟进。谢谢!
document.getElementById("save").addEventListener
(
"click",
function ()
{
var userEmail = document.getElementById("getEmail").value;
var formData = new FormData();
formData.append("extension_user", userEmail);
var channel;
var socket;
var handler =
{
//I changed this to "onmessage" as draevor's answer but
//I still don't see "evt.data" logged
onMessage: function (evt)
{
//evt.data will be what the server sends in channel.send_message
console.log("evt.data received from authhandler: " + evt.data);
alert("evt.data is: " + evt.data)
}
};
var xhr = new XMLHttpRequest();
xhr.onReadyStateChange = function()
{
//this alert does not trigger
alert("xhr.onReadyStateChange")
if (xhr.readyState == 4 && xhr.status == 200)
{
token = xhr.responseText;
//this alert does not trigger
alert("token: " + token)
channel = new goog.appengine.Channel(token);
socket = channel.open(handler);
}
};
xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
xhr.send(formData);
console.log("formData sent to authsender: " + formData);
}, false
)
更新
根据draevor's answer的建议进行更新我添加了onmessage
的其他属性。我跟着this question,虽然我不确定他为什么把这些属性放在单引号中。
document.getElementById("save").addEventListener
(
"click",
function ()
{
var userEmail = document.getElementById("getEmail").value;
var formData = new FormData();
formData.append("extension_user", userEmail);
var channel;
var socket;
var handler =
{
onopen: onOpen,
onmessage: onMessage,
onerror: onError,
onclose: onClose
};
var xhr = new XMLHttpRequest();
xhr.onReadyStateChange = function()
{
//this alert does not trigger
alert("xhr.onReadyStateChange")
if (xhr.readyState == 4 && xhr.status == 200)
{
token = xhr.responseText;
//this alert does not trigger
alert("token: " + token)
channel = new goog.appengine.Channel(token);
socket = channel.open(handler);
}
};
xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
xhr.send(formData);
console.log("formData sent to authsender: " + formData);
}, false
)
onMessage =
function (evt)
{
//evt.data will be what the server sends in channel.send_message
console.log("evt.data received from authhandler: " + evt.data);
alert("evt.data is: " + evt.data)
}
onOpen =
function ()
{
alert("onOpen")
}
onError =
function ()
{
alert("onError")
}
onClose =
function ()
{
alert("onClose")
}
答案 0 :(得分:1)
我认为问题只是将属性命名为onMessage
而不是onmessage
。我还建议设置所有其他属性(onopen
,onerror
,onclose
),至少出于调试目的,以防上述情况无法解决您的问题。
答案 1 :(得分:1)
window.onmessage用于在帧之间发送消息。 Channel API使用它。所以,如果你创建了自己的window.onmessage - 你在这里做的 - 所有的东西都会松动。
只需内联定义处理程序,或完全将其称为其他内容(handleChannelMessage或what-have-you)。