为空

2012-02-24 31 views
0

为什么这个函数返回响应我的事件点击写了一个函数如下为空

$('#ClickMe').live('click', function() { 
    chrome.extension.sendRequest({ method: "getT" }, function (response) { 
     alert(response.data); // Displaying undefined.. 
    }); 
}); 
在后台页面

..

function wish(){  
    return "Hey..."; 
} 
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){ 
    if (request.method == "getT"){ 
    sendResponse({data: wish()}); 
    } 
    else 
    sendResponse({}); 
}); 

我不能在内容Script.Please帮助响应我在这。

+0

您是否曾尝试在背景页面添加'console.log()'语句来查看究竟是什么被调用以及何时以及request.method的值?代码对我来说看起来很好,我想不出为什么它不起作用。 – Alasdair 2012-02-24 13:23:30

+0

我无法重现该错误。你如何运行'$(“#ClickMe”.....);'? – 2012-02-24 13:33:55

+0

@Rob W我无法理解你的观点。你能告诉我你想要什么更多的输入...... – Exception 2012-02-24 14:01:27

回答

1

你不能在JSON对象中发送那样的函数参数,你需要首先实例化它,然后把它作为一个变量传递,而不是作为一个函数,因为它将它视为一个Closure,所以当它执行序列化时,它不会包括这一点。

function wish(){  
    return "Hey..."; 
} 
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){ 
    if (request.method == "getT"){ 
    var data = wish(); 
    sendResponse({data: data}); 
    } 
    else 
    sendResponse({}); 
}); 

上面的代码片段应该工作。

+0

很高兴收到你的回复,并感谢你的回答。 – Exception 2012-02-25 12:45:37