Chrome 扩展 - 在“onclick”回调函数中创建一个 javascript XMLHttpRequest

发布于 2024-10-17 03:27:58 字数 503 浏览 1 评论 0原文

我有以下问题: 我正在尝试为使用上下文菜单的 Chrome 扩展编写 JavaScript 代码。

var id = chrome.contextMenus.create({"title": "search Flickr", "contexts":"selection","onclick":searchSelection});

function searchSelection(info,tab){
var xhReq = new XMLHttpRequest();
 xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false);
 xhReq.send(null);
 var serverResponse = xhReq.responseText;
 alert(serverResponse); // Shows "15"

}

正如你所看到的,我正在尝试在此函数中创建一个 http 请求。由于某种原因,这不起作用。 怎么了? 谢谢, 玛丽

I have the following question:
I am trying to write a javascript code for a chrome extension that uses context menus.

var id = chrome.contextMenus.create({"title": "search Flickr", "contexts":"selection","onclick":searchSelection});

function searchSelection(info,tab){
var xhReq = new XMLHttpRequest();
 xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false);
 xhReq.send(null);
 var serverResponse = xhReq.responseText;
 alert(serverResponse); // Shows "15"

}

as you can see I am trying to create an http request at this function. for some reason this doesn't work.
what is wrong?
Thanks,
Mary

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的背包 2024-10-24 03:27:58

最好使用异步 XMLHttpRequest,同步调用会阻塞浏览器,这可能会导致糟糕的用户体验。

对于异步请求,您必须使用回调处理程序,因为没有它您将无法获取 responseText。当你做这样的事情时它会起作用吗:

function searchSelection(info,tab){
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", true);
    xhReq.onreadystatechange = function () {
        if (xhReq.readyState == 4) {
            if (xhReq.status == 200) {
                var serverResponse = xhReq.responseText;
                alert(serverResponse); // Shows "15"
            }
        }
    };
    xhReq.send();
}

It's always better to use an asynchronous XMLHttpRequest, a synchronous call will block the browser, which might lead to a bad user experience.

With an asynchronous request you'll have to use a callback handler, because without it you won't be able to get the responseText. Does it work when you do something like this:

function searchSelection(info,tab){
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", true);
    xhReq.onreadystatechange = function () {
        if (xhReq.readyState == 4) {
            if (xhReq.status == 200) {
                var serverResponse = xhReq.responseText;
                alert(serverResponse); // Shows "15"
            }
        }
    };
    xhReq.send();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文