开发者

Using XMLHttpRequest in a Google Chrome extension

开发者 https://www.devze.com 2023-01-07 04:12 出处:网络
I started making this simple google chrome extension in javascript. And in the beginning of the code I have the following:

I started making this simple google chrome extension in javascript. And in the beginning of the code I have the following:

var req = new XMLHttpRequest();

req.open(
    "GET",
    "http://www.ldoceonline.com/dictionary/manga",
    true);

req.onreadystatechange(alert(req.readyState));

The value req.readyState comes to be 1, which means the required page开发者_JAVA百科 has not been properly fetched. I'm a newbie to Javascript. What's the problem in my code?


how about something like this

var request = new XMLHttpRequest();

if (request == null){
        alert("Unable to create request");
    }else{

        var url = "http://www.ldoceonline.com/dictionary/manga";

        request.onreadystatechange = function()
            {
            if(request.readyState == 4)
            {
                LDResponse(request.responseText);
            }
        }

        request.open("GET", url, true);
        request.send(null);
    }

function LDResponse(response)
{
// do stuff with the response
}

Of course this is all assuming that they are giving you valid data back ie XML or json


On this line:

req.onreadystatechange(alert(req.readyState));

alert() is being called straight away, which I'm sure isn't your intention. It seems that you want to wait for the onreadystatechange event to fire and then alert the readyState. If that's the case then try this:

req.onreadystatechange = function() {
    alert(req.readyState);
};

And don't forget req.send(null)!

0

精彩评论

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