使用 JavaScript 发送 HTTP 请求?

Send HTTP request using JavaScript?

我正在尝试使用 GET 请求从 http://api.roblox.com/marketplace/productinfo?assetId=361192737 (link) 获取一个 JSON 对象,但它似乎不起作用。

(function(){
    var xmlHttp;
    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", 'http://api.roblox.com/marketplace/productinfo?assetId=361192737', true );
    xmlHttp.send( null );
    function ProcessRequest(){
        console.log(xmlHttp.responseText); // "" (empty string)
        var respData = JSON.parse(xmlHttp.responseText) || {};
        RemoteEvents = JSON.parse(respData.Description) || null;
    }
})()

这是开发模式下的 Chrome 扩展。我对 JavaScript 不是很有经验,对 HTTP 请求就更不用说了。我做错了什么?

回调“onreadystatechange”将使用不同的“状态代码”调用多次。 您必须在尝试获取数据之前检查代码以确保请求已结束。 完成后的代码值为4,看这里: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

这应该有效:

(function(){
    var xmlHttp;
    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            console.log(xmlHttp.responseText); // "" (empty string)
            var respData = JSON.parse(xmlHttp.responseText) || {};
            RemoteEvents = JSON.parse(respData.Description) || null;
        }
    };
    xmlHttp.open( "GET", 'http://api.roblox.com/marketplace/productinfo?assetId=361192737', true );
    xmlHttp.send( null );
})();