javascript - JSON获取一个值(很菜鸟)

标签 javascript json

大家好,我有一个 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 之前。

Here is a live example.

节点.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/

相关文章:

javascript - 我可以从 Java 9 Nashorn 引擎运行 ECMAScript 6 吗

javascript - 单击子 td 时如何获取 th ?

javascript - 使用 Dust.js 的异步自关闭助手

python - 在 json 中发送 NaN

ios - 来自 json 数组的 TableView 中的 imageView

javascript - AngularJS - 级联动态选择列表

javascript - 如何销毁小部件同时保留它所附加的根节点?

javascript - 需要在网页上设置最小高度

PHP 将 JSON 数据从 Android 插入 MySQL 数据库

javascript - 将 Backbone 模型和集合保存到 JSON 字符串