如何获取并使用JSON参数值从API请求/响应 [英] How to get and use a JSON parameter value from an API request/response

查看:131
本文介绍了如何获取并使用JSON参数值从API请求/响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个网站,要显示或隐藏一个div标签取决于参数值,我可以在API响应中找到。

链接到我所需要的API的信息是 https://api.hitbox.tv/media /状态/ MASTA 其中MASTA换成我的频道名称。该反应是这样的: {media_is_live:0,media_views:2}

我preFER只使用纯JavaScript,但尝试以下使用AJAX的code,但没有奏效。我不熟悉JavaScript,jQuery和AJAX,所以也许我做了一些错误的code写为好。有什么建议?

 <脚本SRC =htt​​ps://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / SCRIPT&GT ;

<脚本>
$(文件)。就绪(函数(){
    $阿贾克斯({
        键入:GET,
        数据类型:JSON,
        网址:https://api.hitbox.tv/media/status/masta
        数据:media_is_live
        成功:功能(数据){
            如果(数据==0){
                。的document.getElementById(玩家)style.visibility =隐藏;
            }
            其他 {
                。的document.getElementById(玩家)style.visibility =看得见;
            }
        }
    });
});
< / SCRIPT>

< D​​IV ID =运动员与GT; [LIVESTREAM-PLAYER] LT; / DIV>
 

解决方案

您Ajax调用应该是这样的。

该media_is_live是结果,而不是在你的查询。

  $。阿贾克斯({
    键入:GET,
    数据类型:JSON,
    网址:https://api.hitbox.tv/media/status/masta
    成功:功能(数据){
        如果(data.media_is_live ==0){
            //你的code在这里
        }
        其他 {
            //你的code在这里
        }
    }
});
 

I'm working on a website and want to display or hide a div-tag depending on a parameter value I can find in an API response.

The link to the API information I need is https://api.hitbox.tv/media/status/masta where "masta" is replaced by my channel-name. The response looks like this: {"media_is_live":"0","media_views":"2"}

I prefer to only use pure javascript, but tried the code below using AJAX but didn't work. I'm not familiar with javascript, jQuery and AJAX so maybe I did some wrong code writing as well. Any suggestions?:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "https://api.hitbox.tv/media/status/masta",
        data: "media_is_live",
        success: function(data){
            if(data == "0") {
                document.getElementById("player").style.visibility = "hidden";
            }
            else {
                document.getElementById("player").style.visibility = "visible";
            }
        }
    });
});
</script>

<div id="player">[LIVESTREAM-PLAYER]</div>

解决方案

Your ajax call should look like this.

The media_is_live is in the result, not in your query.

$.ajax({
    type: "GET",
    dataType: "json",
    url: "https://api.hitbox.tv/media/status/masta",
    success: function(data){
        if(data.media_is_live == "0") {
            //Your code here
        }
        else {
            //Your code here
        }
    }
});

这篇关于如何获取并使用JSON参数值从API请求/响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆