【问题标题】:How to call parameters from an API (json) in html如何从 html 中的 API (json) 调用参数
【发布时间】:2015-10-23 15:13:57
【问题描述】:

我创建了my own API,想知道如何调用参数? 我一直在尝试使用以下代码调用“type”参数,但它未定义......即使我只记录“json”,控制台中也没有任何显示......

谁能告诉我我哪里做错了?

非常感谢!!! :))) xxx

		<canvas id="myCanvas"> </canvas>
		<script type="text/javascript" src="js/jQuery.js"></script>
		<script type="text/javascript">

			var canvas = document.getElementById("myCanvas");
			var ctx = canvas.getContext("2d");
			ctx.canvas.width = window.innerWidth;
			ctx.canvas.height = window.innerHeight;

			$(document).ready(function(){ 	

			var ctx = canvas.getContext("2d");

			ctx.beginPath();
				ctx.fillStyle = "rgb(255,255,255)";
				ctx.fillRect(0,0,canvas.width, canvas.height);

				var url = "https://sheetsu.com/apis/f924526c"; 


			$.getJSON(url,function(json){
			
                                console.log(json);

				var type = json.type;
				$('type').append(type);
				console.log(type);

			});
		});

		</script>

【问题讨论】:

    标签: html json api parameters


    【解决方案1】:

    查看你从服务器获取的部分 JSON 数据:

    {
      "status": 200,
      "success": true,
      "result": [
        {
          "number": "0",
          "URL random digit1": "1",
          "URL random digit2": "8",
          "id": "1a8",
          "name": "user1",
          "type": "mf",
          "url": "http://test.com/customised_url_1a8",
          "message": "bonjour user1"
        },
    ....
    

    据此,您应该通过以下方式访问第 0 个元素的“类型”:

    json.result[0].type
    

    请注意,您的 json 在接收时会转换为 JS 对象。您应该遵循对象的方案来访问它的任何属性。

    【讨论】:

    • 您好查理,非常感谢您的回复。我试着像这样改变它,但控制台仍然没有任何结果...... $.getJSON(url,function(json){ v​​ar type = json.result[0].type; $('type') .append(type); console.log(type); });
    • 请创建一个小提琴。然后我就明白为什么了。请注意,您不需要在小提琴中放置画布。只需包含相关代码,并确保它符合我们在此处讨论的内容。
    • 您的问题出在这一行:$('type').append(type);。如果删除此行,控制台会显示类型。请按照 JQuery 教程了解$ 函数的正确使用方法。
    猜你喜欢
    • 2020-12-31
    • 2012-10-31
    • 1970-01-01
    • 2017-03-06
    • 2018-10-21
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多