简体   繁体   English

使用JavaScript发送HTTP请求?

[英]Send HTTP request using JavaScript?

I'm trying to get a JSON object from http://api.roblox.com/marketplace/productinfo?assetId=361192737 ( link ) using a GET request, but it doesn't seem to be working. 我正在尝试使用GET请求从http://api.roblox.com/marketplace/productinfo?assetId=361192737链接 )获取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;
    }
})()

This is on a Chrome Extension in Development Mode. 这是在开发模式下的Chrome扩展程序上。 I'm not very experienced with JavaScript, and even less with HTTP requests. 我对JavaScript不太有经验,而对HTTP请求的经验则更少。 What am I doing wrong? 我究竟做错了什么?

The callback " onreadystatechange " will be called multiple times with different " state codes ". 回调“ onreadystatechange”将使用不同的“状态码”多次调用。 You have to check the code before trying to get the data to be sure that the request ended. 您必须在尝试获取数据之前检查代码,以确保请求已结束。 The code value when it finished is 4, have a look here : http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp 完成后的代码值为4,请在此处查看: http : //www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

This should work : 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM