我尝试使用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请求的帮助也更少。我做错了什么?
答案 0 :(得分:2)
将使用不同的“状态代码”多次调用回调“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 );
})();