从API问题集成Cricket即将到来的匹配

时间:2017-08-10 06:18:51

标签: javascript php ajax api

我正在尝试整合来自API的板球即将到来的比赛,但我不知道我哪里出错了。

我是JSON的新手请帮我从JSON(在API中)获取值,我使用 XXXX 变量隐藏了我的API密钥,

我尝试使用提示它不打印任何内容:

代码:

<script>
  $.ajax({ 
type: 'GET', 
url: 'http://cricapi.com/api/cricket/?apikey=XXXX', 
dataType: 'json',
success: function(data){ 
    $.each(this, function(key, value) {

            container.append(key + ':' +value );
            alert(key);
        }
        ));
        container.append('<br/></br>');
    });
});

</script>   

现在iam添加了下面的json文件

{"data":[{"title":"Somerset 436/10  v Surrey 69/1 *","description":"Somerset 436/10  v Surrey 69/1 *","unique_id":"1068564"},{"title":"Zimbabwe A v South Africa Emerging Players 298/4 *","description":"Zimbabwe A v South Africa Emerging Players 298/4 *","unique_id":"1114833"},{"title":"Trinbago Knight Riders 147/10  v Jamaica Tallawahs 148/6 *","description":"Trinbago Knight Riders 147/10  v Jamaica Tallawahs 148/6 *","unique_id":"1094678"},{"title":"Band-e-Amir Region 92/2 * v Speen Ghar Region","description":"Band-e-Amir Region 92/2 * v Speen Ghar Region","unique_id":"1115759"},{"title":"Mis Ainak Region v Amo Region 91/2 *","description":"Mis Ainak Region v Amo Region 91/2 *","unique_id":"1115760"},{"title":"Southern Vipers v Western Storm","description":"Southern Vipers v Western Storm","unique_id":"1093476"},{"title":"Lyca Kovai Kings v Madurai Super Giant","description":"Lyca Kovai Kings v Madurai Super Giant","unique_id":"1107276"},{"title":"Middlesex v Sussex","description":"Middlesex v Sussex","unique_id":"1068394"},{"title":"Hampshire v Glamorgan","description":"Hampshire v Glamorgan","unique_id":"1068393"},{"title":"St Lucia Stars v Barbados Tridents","description":"St Lucia Stars v Barbados Tridents","unique_id":"1094679"}],"cache":false,"v":"1","ttl":342,"provider":{"source":"Various","url":"https://cricapi.com/","pubDate":"2017-08-10T07:00:36.898Z"},"creditsLeft":249}

1 个答案:

答案 0 :(得分:0)

我认为错误是您this上的each。它应该是data或data.data。关闭)和}也存在一些问题。这是一个可以的例子。

function myFunc(){
		var container=document.getElementById("cont");
		alert(container);
		$.ajax({
		 	type: 'GET', 
		 	url: 'http://cricapi.com/api/cricket/?apikey=TESTKEY0273', 
		 	dataType: 'json',
		 	success: function(data) {
		 		$.each(data.data, function(key, value) {
		 			container.append(key + ':' +value.description +" <br />\n");
		 		});
		 	}
		});
             
	  }
    
$(document).ready(myFunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="cont"></div>