最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Using XMLHttpRequest in a Google Chrome extension - Stack Overflow

matteradmin7PV0评论

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",
    "",
    true);

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

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

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./dictionary/manga",
    true);

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

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

Share Improve this question edited Jul 13, 2010 at 14:13 James 112k32 gold badges164 silver badges177 bronze badges asked Jul 13, 2010 at 14:12 thameerathameera 9,51310 gold badges38 silver badges40 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

how about something like this

var request = new XMLHttpRequest();

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

        var url = "http://www.ldoceonline./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)!

Post a comment

comment list (0)

  1. No comments so far