从Hearthstone API中提取JSON数据。

时间:2021-10-11 09:51:09

I am trying to create a random Hearthstone card generator and I am having trouble with pulling the JSON data from the API and converting it into a JS object so I can input the text into my HTML. I have tested the request on request maker so the API request works fine, however theres obviously some other problem that I'm missing. I've tried the various syntax for converting the JSON data into a JS object, but it's just not working. Im thinking that maybe there's something wrong with the callback function I put into the success key/value pair. Nevertheless I've looked quite a bit for a solution and I have changed up a few things but it's not working. Any help would be appreciated!

我正在尝试创建一个随机的炉石卡片生成器,我在从API提取JSON数据并将其转换为一个JS对象时遇到了麻烦,因此我可以将文本输入到我的HTML中。我已经对请求创建器进行了测试,所以API请求可以正常工作,但是显然还有一些其他问题我没有解决。我尝试过将JSON数据转换为JS对象的各种语法,但它就是不能工作。我在想,我在成功键/值对中放入的回调函数可能有问题。尽管如此,我还是找了不少解决办法,我也做了一些改变,但都没有用。如有任何帮助,我们将不胜感激!

So what I would like to happen is when that next button is clicked, it will retrieve the data and input it into the specified elements on the screen. The data I am trying to grab is all cards with the only parameter Im using is the collectable one, so I'd like to pull a random card each time the arrow is clicked.

因此,我希望发生的是,当下一个按钮被单击时,它将检索数据并将其输入到屏幕上指定的元素中。我要抓取的数据都是所有的卡片,而Im使用的唯一参数是可收集的卡片,所以每次单击箭头时我都要随机抽取一张卡片。

Also,here is a link to the API itself: https://market.mashape.com/omgvamp/hearthstone.

此外,这里还有一个到API本身的链接:https://market.mashape.com/omgvamp/hearthstone。

var cardImage = '', cardName = '', cardType = '', cardFaction = '',
 cardRarity = '', playerClass = '', artistName = '';
function cardInfo() {

    $.ajax({
        type: "POST",
        url: "https://omgvamp-hearthstone-v1.p.mashape.com/cards? collectible=1",
        headers: {
            "x-mashape-key": "mXtnPm3ltOmshc9dQJjtVdKzfnhbp14UZncjsnfzwvp6uLiMwH",
            Accept: "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (response) {
            var obj = jQuery.parseJSON(response);
            cardImage = obj.image;
            cardName = obj.name;
            cardType = obj.type;
            cardFaction = obj.faction;
            cardRarity = obj.rarity;
            playerClass = obj.playerClass;
            artistName = obj.artist;

            $("#card-image").attr(src, obj.image);
            $("#card-name").html(obj.name);
            $("#card-type").text(obj.type);
            $("#card-faction").text(obj.faction);
            $("#card-rarity").text(obj.rarity);
            $("#player-class").text(obj.playerClass);
            $("#artist-name").text(obj.artist);
        },
        dataType: "json"
    })
}

$(document).ready(function () {
    $('#nextCard').click(cardInfo())
});

$(document).ready(function() {
    $('#nextCard').click(cardInfo())
});

2 个解决方案

#1


2  

You were pretty much there - just needed to tweak the request a little - the docs specify a GET request for that particular endpoint. Your request was responding with {"error":400,"message":"Token mismatch exception."} with a 400 HTTP status code.

您已经在那里了——只需稍微调整一下请求——文档为特定的端点指定了一个GET请求。您的请求使用了{“错误”:400,“消息”:“令牌错配异常”。具有400个HTTP状态码的}。

Also cards are returned in their sets (classic/naxx/etc.) so I've flattened the object a little to make selecting a random card easier. I also tweaked the request to better reflect the mashape docs http://docs.mashape.com/javascript.

另外,卡片也会返回到它们的集合中(经典的/naxx/等等),所以我将对象变平了一点,以便更容易地选择随机的卡片。我还调整了请求以更好地反映mashape docs http://docs.mashape.com/javascript。

You also missed the quotes around 'src' when trying to set the images src attribute and obj.image is undefined and should have been obj.img

当您试图设置图像src属性和obj时,您也会漏掉“src”的引号。图像是未定义的,应该是object .img。

Finally I removed a few superfluous variables.

最后我去掉了一些多余的变量。

Click the next button to perform a request (One isn't triggered initially) also it was a little slow to respond for me so give it a few secs.

单击next按钮来执行一个请求(一个请求最初没有被触发),而且它对我的响应有点慢,所以给它一些时间。

var cards;
var dataPromise;

function getCardData() {
  if(!dataPromise){
    dataPromise = $.ajax({ // Store jQuery promise so that we can return it for subsequent calls ensuring only one AJAX request is made
      url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1',
      type: 'GET',
      dataType: 'json',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("X-Mashape-Authorization", "mXtnPm3ltOmshc9dQJjtVdKzfnhbp14UZncjsnfzwvp6uLiMwH");
      }
    });
  } 
  return dataPromise;
}

function showCardRandom(){
  var cardNo = Math.floor(Math.random() * cards.length); // Select a random card number
  showCard(cardNo)
}

function showCard(cardNo){
  var obj = cards[cardNo];
  $("#card-image").attr('src', obj.img);
  $("#card-name").html(obj.name);
  $("#card-type").text(obj.type);
  $("#card-faction").text(obj.faction);
  $("#card-rarity").text(obj.rarity);
  $("#player-class").text(obj.playerClass);
  $("#artist-name").text(obj.artist);
}

function flattenCards(data){
    // Flatten the object as cards are stored in sets
    var result = [];
    for (var set in data) {
      for (var i = 0; i < data[set].length; i++) {
        result.push(data[set][i]);
      }
    }
    return result;
}

getCardData(); // Start loading card data ASAP - subsequent calls will return the same promise anyway

$(document).ready(function() {
  getCardData()
    .done(function(data){
       $("#nextCard").text("Next");
       cards = flattenCards(data);
       showCardRandom();
    });
  $('#nextCard').click(showCardRandom);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="card-image">
<div id="card-name"></div>
<div id="card-type"></div>
<div id="card-faction"></div>
<div id="card-rarity"></div>
<div id="player-class"></div>
<div id="artist-name"></div>
<button id="nextCard">Loading Data...</button>

#2


0  

If the response is of type json then try doing it this way.

如果响应类型为json,那么尝试这样做。

 var cardImage = JObject.Parse(response.Result).GetValue("image");

I hope this helps you.

我希望这能帮到你。

#1


2  

You were pretty much there - just needed to tweak the request a little - the docs specify a GET request for that particular endpoint. Your request was responding with {"error":400,"message":"Token mismatch exception."} with a 400 HTTP status code.

您已经在那里了——只需稍微调整一下请求——文档为特定的端点指定了一个GET请求。您的请求使用了{“错误”:400,“消息”:“令牌错配异常”。具有400个HTTP状态码的}。

Also cards are returned in their sets (classic/naxx/etc.) so I've flattened the object a little to make selecting a random card easier. I also tweaked the request to better reflect the mashape docs http://docs.mashape.com/javascript.

另外,卡片也会返回到它们的集合中(经典的/naxx/等等),所以我将对象变平了一点,以便更容易地选择随机的卡片。我还调整了请求以更好地反映mashape docs http://docs.mashape.com/javascript。

You also missed the quotes around 'src' when trying to set the images src attribute and obj.image is undefined and should have been obj.img

当您试图设置图像src属性和obj时,您也会漏掉“src”的引号。图像是未定义的,应该是object .img。

Finally I removed a few superfluous variables.

最后我去掉了一些多余的变量。

Click the next button to perform a request (One isn't triggered initially) also it was a little slow to respond for me so give it a few secs.

单击next按钮来执行一个请求(一个请求最初没有被触发),而且它对我的响应有点慢,所以给它一些时间。

var cards;
var dataPromise;

function getCardData() {
  if(!dataPromise){
    dataPromise = $.ajax({ // Store jQuery promise so that we can return it for subsequent calls ensuring only one AJAX request is made
      url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1',
      type: 'GET',
      dataType: 'json',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("X-Mashape-Authorization", "mXtnPm3ltOmshc9dQJjtVdKzfnhbp14UZncjsnfzwvp6uLiMwH");
      }
    });
  } 
  return dataPromise;
}

function showCardRandom(){
  var cardNo = Math.floor(Math.random() * cards.length); // Select a random card number
  showCard(cardNo)
}

function showCard(cardNo){
  var obj = cards[cardNo];
  $("#card-image").attr('src', obj.img);
  $("#card-name").html(obj.name);
  $("#card-type").text(obj.type);
  $("#card-faction").text(obj.faction);
  $("#card-rarity").text(obj.rarity);
  $("#player-class").text(obj.playerClass);
  $("#artist-name").text(obj.artist);
}

function flattenCards(data){
    // Flatten the object as cards are stored in sets
    var result = [];
    for (var set in data) {
      for (var i = 0; i < data[set].length; i++) {
        result.push(data[set][i]);
      }
    }
    return result;
}

getCardData(); // Start loading card data ASAP - subsequent calls will return the same promise anyway

$(document).ready(function() {
  getCardData()
    .done(function(data){
       $("#nextCard").text("Next");
       cards = flattenCards(data);
       showCardRandom();
    });
  $('#nextCard').click(showCardRandom);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="card-image">
<div id="card-name"></div>
<div id="card-type"></div>
<div id="card-faction"></div>
<div id="card-rarity"></div>
<div id="player-class"></div>
<div id="artist-name"></div>
<button id="nextCard">Loading Data...</button>

#2


0  

If the response is of type json then try doing it this way.

如果响应类型为json,那么尝试这样做。

 var cardImage = JObject.Parse(response.Result).GetValue("image");

I hope this helps you.

我希望这能帮到你。