Okey,我从2个不同的JSON文件中获取了一些数据,我想把它们中的一个与另一个分开,我该怎么做?我想分开' sugString'使用' htmlString'。在我完成之后,我想将它插入到不同的ID中,就像我已经对它们中的每一个一样。
var flamingSkull = document.getElementById("flaming-skull");
var flamingSkullq = document.getElementById("flaming-skullq");
var flamingSkullSug = document.getElementById("flaming-skullsug");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=433850');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
renderFlamingSkull(ourData);
};
ourRequest.send();
var ourRequest2 = new XMLHttpRequest();
ourRequest2.open('GET', 'https://api.opskins.com/IPricing/GetPriceList/v1/?appid=433850');
ourRequest2.onload = function() {
var ourData2 = JSON.parse(ourRequest2.responseText);
renderFlamingSkullSug(ourData2);
};
ourRequest2.send();
function renderFlamingSkullSug(data) {
var sugString = data.response[ 'Skin: Flaming Skull Face Bandana' ][today].price / 100;
flamingSkullSug.insertAdjacentHTML('beforeend', "$" + sugString);
}
function renderFlamingSkull(data) {
var htmlString = data.response[ 'Skin: Flaming Skull Face Bandana' ].price / 100;
var quantityString = data.response[ 'Skin: Flaming Skull Face Bandana' ].quantity;
flamingSkull.insertAdjacentHTML('afterbegin', "$" + htmlString);
flamingSkullq.insertAdjacentHTML('beforeend', "<p>(" + quantityString + ")</p>");
}
答案 0 :(得分:0)
一种解决方案是创建请求函数并对其使用回调。因此,您可以将这两个请求链接在一起,并可以访问这两个请求。
var flamingSkull = document.getElementById("flaming-skull");
var flamingSkullq = document.getElementById("flaming-skullq");
var flamingSkullSug = document.getElementById("flaming-skullsug");
var lowestPriceUrl = 'https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=433850';
var priceListUrl = 'https://api.opskins.com/IPricing/GetPriceList/v1/?appid=433850';
function makeRequest (method, url, done) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
done(null, JSON.parse(xhr.responseText));
};
xhr.onerror = function () {
done(JSON.parse(xhr.responseText));
};
xhr.send();
}
makeRequest('GET', lowestPriceUrl, function (err, res) {
if (err) { throw err; }
makeRequest('GET', priceListUrl, function (err, res2) {
if (err) { throw err; }
var sugString = res[ 'Skin: Flaming Skull Face Bandana' ][today].price / 100;
var htmlString = res2[ 'Skin: Flaming Skull Face Bandana' ].price / 100;
var quantityString = res2[ 'Skin: Flaming Skull Face Bandana' ].quantity;
flamingSkullSug.insertAdjacentHTML('beforeend', "$" + sugString);
flamingSkull.insertAdjacentHTML('afterbegin', "$" + htmlString);
flamingSkullq.insertAdjacentHTML('beforeend', "<p>(" + quantityString + ")</p>");
// Complete division
// ==================
// var division = Math.round(sugString/htmlString)
});
});
&#13;
使用其他问题作为参考:How do I promisify native XHR?