首页 > 解决方案 > 通过 jQuery 实现 Foursquare API 来查找餐厅

问题描述

我正在做一个项目,我通过 Fetch 和 jQuery 使用 Foursquare API 搜索附近的餐馆,但我无法显示结果。我能够通过 Postman 获得结果,但我不确定为什么我的结果没有显示。

我已经设置了一个带有搜索栏的基本网站,您可以在其中搜索哪个城市以及在一页中返回的结果数量。我的问题是我做错了什么或者我错过了什么,以便我可以在网页上显示结果?

'use strict';

// put your own value below!
const clientID = '0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC'; 
const clientSecret = 'KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY'
const searchURL = 'https://api.foursquare.com/v2/venues/search';
const ver = '20201120'

function formatQueryParams(params) {
  const queryItems = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  return queryItems.join('&');
}

function displayResults(responseJson) {
  // if there are previous results, remove them
  console.log(responseJson);
  $('#results-list').empty();
  // iterate through the items array
  for (let i = 0; i < responseJson.items.length; i++){
    //array, add a list item to the results 
    //list with the title and description,
    $('#results-list').append(
      `<li><h3><a href="${responseJson.value[i].canonicalUrl}">${responseJson.value[i].name}</a></h3>
      <p>${responseJson.value[i].description}</p>
      <p>${responseJson.value[i].body}</p>
      </li>`
    )}
  //display the results section  
  $('#results').removeClass('hidden');

}



function getRestaurants(location, maxResults=10) {
  const params = {
    id: clientID,
    secret: clientSecret,
    near: location,
    maxResults,
  };
  console.log(params)
  //create a string with the original URL and the new parameter
  const queryString = formatQueryParams(params)
  const url = searchURL + '?client_id=' + clientID + '&client_secret=' + clientSecret + queryString;


function jsonCallback(json){ 
  console.log("Foursquare API result:", json); }

$.ajax({
  dataType: "json",
  url: "https://api.foursquare.com/v2/venues/search?client_id=0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC&client_secret=KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY&v=20201120&limit=10&near=" + location + "&query=restaurants",
  data: {},
  success: function(data) {
    // Code for handling API response
    console.log(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // Code for handling errors
  }
});

console.log(url);

fetch('https://api.foursquare.com/v2/venues/51db1d29498e99e8c8b72d52?client_id=0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC&client_secret=KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY&v=20201120')
  .then(rawResponse=> {
  if (rawResponse.ok) {
    return rawResponse.json();
  }
}).then(response=>{
  console.log(response);
})
.catch(err => {
  $('#js-error-message').text(`Something went wrong: ${err.message}`);
});

  // fetch sample
  // fetch(url)
  //   .then(response => {
  //     if (response.ok) {
  //       return response.json();
  //     }
  //     throw new Error(response.statusText);
  //   })
  //   .then(responseJson => displayResults(responseJson))
  //   .catch(err => {
  //     $('#js-error-message').text(`Something went wrong: ${err.message}`);
  //   });
}

function watchForm() {
  $('form').submit(event => {
    event.preventDefault();
    const searchTerm = $('#js-search-term').val();
    const maxResults = $('#js-max-results').val();
    getRestaurants(searchTerm, maxResults);
  });
}

$(watchForm);
  .hidden {
    display: none;
  }
  
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>COVID Open Restaurants</title>
    <link rel="shortcut icon" href="">
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <!-- Title -->
    <header class="title">
        <h1>COVID Open Restaurants</h1>
        <nav>
            <a href="index.html">Home</a>
            <a href=""></a>
        </nav>
        <form id="js-form">
            <label for="search-term">Search for your city</label>
            <input type="text" name="search-term" id="js-search-term" required>

            <label for="max-results">Maximum results to return</label>
            <input type="number" name="max-results" id="js-max-results" value="10">

            <input type="submit" value="Go!">
        </form>

        <p id="js-error-message" class="error-message"></p>
        <section id="results" class="hidden">
          <h2>Search results</h2>
          <ul id="results-list">
          </ul>
        </section>
    </header>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>
</html>

标签: jqueryfoursquarecapstone

解决方案


您的代码中有很多...杂乱无章,以至于我实际上无法分辨哪个调用正在返回有用的数据。但是我修改了您$.ajax成功函数中的代码以显示餐厅名称列表。您可以遵循该一般模式。

'use strict';

// put your own value below!
const clientID = '0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC'; 
const clientSecret = 'KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY'
const searchURL = 'https://api.foursquare.com/v2/venues/search';
const ver = '20201120'

function formatQueryParams(params) {
  const queryItems = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  return queryItems.join('&');
}

function displayResults(responseJson) {
  // if there are previous results, remove them
  //console.log(responseJson);
  $('#results-list').empty();
  // iterate through the items array
  for (let i = 0; i < responseJson.items.length; i++){
    //array, add a list item to the results 
    //list with the title and description,
    $('#results-list').append(
      `<li><h3><a href="${responseJson.value[i].canonicalUrl}">${responseJson.value[i].name}</a></h3>
      <p>${responseJson.value[i].description}</p>
      <p>${responseJson.value[i].body}</p>
      </li>`
    )}
  //display the results section  
  $('#results').removeClass('hidden');

}



function getRestaurants(location, maxResults=10) {
  const params = {
    id: clientID,
    secret: clientSecret,
    near: location,
    maxResults,
  };
  console.log(params)
  //create a string with the original URL and the new parameter
  const queryString = formatQueryParams(params)
  const url = searchURL + '?client_id=' + clientID + '&client_secret=' + clientSecret + queryString;


function jsonCallback(json){ 
  console.log("Foursquare API result:", json); }

$.ajax({
  dataType: "json",
  url: "https://api.foursquare.com/v2/venues/search?client_id=0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC&client_secret=KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY&v=20201120&limit=10&near=" + location + "&query=restaurants",
  data: {},
  success: function(data) {
    // Code for handling API response
    //console.log(data.response.venues);
    let ul = document.getElementById("results-list");
    $(data.response.venues).each( (index, venue) => {
        console.log(venue.name);
        ul.innerHTML += `<li>${venue.name}</li>`;
    });
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // Code for handling errors
  }
});

console.log(url);

fetch('https://api.foursquare.com/v2/venues/51db1d29498e99e8c8b72d52?client_id=0J4WJETOBCPLV00I1TVWZZ0OQ4AD0SSR1EF0MHYHYLNLI1UC&client_secret=KGP3X3GVAYN13LUQNUJZS4Q25QHTQJ4ZFMSQVNNAZNNAG2OY&v=20201120')
  .then(rawResponse=> {
  if (rawResponse.ok) {
    return rawResponse.json();
  }
}).then(response=>{
  //console.log(response);
})
.catch(err => {
  $('#js-error-message').text(`Something went wrong: ${err.message}`);
});

  // fetch sample
  // fetch(url)
  //   .then(response => {
  //     if (response.ok) {
  //       return response.json();
  //     }
  //     throw new Error(response.statusText);
  //   })
  //   .then(responseJson => displayResults(responseJson))
  //   .catch(err => {
  //     $('#js-error-message').text(`Something went wrong: ${err.message}`);
  //   });
}

function watchForm() {
  $('form').submit(event => {
    event.preventDefault();
    const searchTerm = $('#js-search-term').val();
    const maxResults = $('#js-max-results').val();
    getRestaurants(searchTerm, maxResults);
  });
}

$(watchForm);
.hidden {
    display: none;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>COVID Open Restaurants</title>
    <link rel="shortcut icon" href="">
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <!-- Title -->
    <header class="title">
        <h1>COVID Open Restaurants</h1>
        <nav>
            <a href="index.html">Home</a>
            <a href=""></a>
        </nav>
        <form id="js-form">
            <label for="search-term">Search for your city</label>
            <input type="text" name="search-term" id="js-search-term" required>

            <label for="max-results">Maximum results to return</label>
            <input type="number" name="max-results" id="js-max-results" value="10">

            <input type="submit" value="Go!">
        </form>

        <p id="js-error-message" class="error-message"></p>
        <section id="results">
          <h2>Search results</h2>
          <ul id="results-list">
          </ul>
        </section>
    </header>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>
</html>


推荐阅读