大家好,我有一个 URL:https://api.csgofast.com/price/all . 现在我想获取给定键(名称)的值(价格)。
我知道已经有一些关于此的问题,但我无法让它工作,而且 JSON 是全新的。
如果可能的话,我希望它在 javascript 中工作。
我希望你们能帮助我:)
我在另一个问题上看到了类似的东西,但无法让它工作:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}
});
我现在得到了这段代码:
getJSON('https://api.csgofast.com/price/all', function(err, data) {
if (err != null) {
console.log("something went wrong on pricing!");
} else {
console.log("item price : " + data['Sticker | Good Game']);
}
});
最佳答案
“不工作”是什么意思?因为 alert
出现了。
浏览器
问题可能是您的result
尚未定义。如果你有:
<div id="result"></div>
然后使用
var result = document.getElementById('result');
在您尝试更改其 innerText
之前。
节点.js
如果您在 Node.js 上运行它,请了解执行 HTTP 请求的不同机制。以下是您需要的代码。
var https = require('https');
var getJSON = function(url, callback) {
https.get(url, function (response) {
var buffer = '';
response.on('error', callback);
response.on('data', function (d) { buffer += d; });
response.on('end', function () {
callback(null, JSON.parse(buffer));
});
});
};
getJSON('https://api.csgofast.com/price/all', function(err, data) {
if (err) {
console.log('Something went wrong: ' + err);
} else {
console.log('item price : ' + data['Sticker | Good Game']);
}
});
关于javascript - JSON获取一个值(很菜鸟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390508/