我正在使用Foursquare API开发API应用程序。使用我的 getRequest , 我的结果是 JSON ,我在控制台 .log中显示。
问题是,我不知道如何解析 JSON数据并在 HTML网页上显示我想要的内容。
我正在尝试显示场地的'name',但我不知道该怎么做。
PS:我对来自Foursquare的传入数据有一个 Math.random 函数,所以我在console.log中显示的随机地点名称就是我想要的显示在我的HTML页面中。
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search</title>
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js" type="text/javascript" id="jquery"></script>
<script type="text/javascript" src="apps/app.js"></script>
</head>
<body>
<H1>Hunger Pains</H1>
<p>Search for food cause you cant take it anymore</p>
<!--This is the area your location gets spit out on the html page-->
<p id="demo"></p>
<form id ="search-term">
<!--text entry field-
<input type="text" id="query">-->
<!--Submit button-->
<input id="submit" type="submit" value="submit">
<!--Search results div-->
<div id="search-results"></div>
</form>
</body>
</html>
Jquery的:
$(document).ready(function(){
//document.getElementById("submit").disabled = false;
//When you click the submit button it fires off the getRequest.
$(function(){
$('#search-term').submit(function(event){
event.preventDefault();
//getRequest();
myFunction();
});
});
// This is the get request. It has a random function that randomizes the callback data. Once you get the randomizes data, it shows in the console window.
//This function displays three random results based on the myFunction below
function getRequest(){
$.getJSON('https://api.foursquare.com/v2/venues/search?v=20131016&ll=40.7%2C-74&intent=browse&radius=800&categoryId=4d4b7105d754a06374d81259&client_id=C2IEUINHBL2HEVOHIWNO0GGN5EUHK3PGYH03HCZRP2ETA4CF&client_secret=DOLF3UBQZOY5GX2DP3EXBQ5CW4AHEWMNDGRMH0IHJWZBDSIO', function(data){
var random = data.response.venues[Math.floor(Math.random() * data.response.venues.length)];
//showResults();
console.log(random);
});
}
//This is the function that calls getRequest function three times then stops.
function myFunction(){
var myVar = setInterval(function(){getRequest();}, 500);
//clearTimeout(myVar);
setTimeout(function( ) { clearInterval( myVar); }, 1600);
}
});
答案 0 :(得分:1)
这样的事情应该这样做:
$("#search-results").append('<br>' + random.name);
答案 1 :(得分:1)
要从Foursquare获取的对象中获取名称,请使用:
console.log(random.name);
如果你需要网址,例如使用:
console.log(random.url);