开发者

Chrome extension- creating a javascript XMLHttpRequest at a function that is called back on 'onclick'

开发者 https://www.devze.com 2023-02-10 15:46 出处:网络
I have the following question: I am trying to write a javascript code for a chrome extension that uses context menus.

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 fun开发者_Go百科ction. for some reason this doesn't work. what is wrong? Thanks, Mary


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消