简体   繁体   English

无法使用jQuery.ajax()从Yelp API检索数据

[英]Cannot retrieve data from Yelp API using jQuery.ajax()

I am trying to use jQuery.ajax() method to retrieve JSON data from Yelp API but its displaying nothing in the console. 我试图使用jQuery.ajax()方法从Yelp API检索JSON数据,但它在控制台中不显示任何内容。

The new Yelp authorization just requires headers to be sent as: 新的Yelp授权只需要将标头发送为:

"Authorization": "Bearer <apikey>"

along with the GET request URL with params. 以及带params的GET请求URL。 Postman is displaying the results but I cannot use it in my API. Postman正在显示结果,但我不能在我的API中使用它。 My code for .ajax goes here: 我的.ajax代码在这里:

var myurl = "https://api.yelp.com/v3/businesses/search?term=by-chloe&location=boston";

$.ajax({
  url: myurl,
  headers: {
    'Authorization': 'Bearer xxxxxxxxxxxxx',
  },
  method: 'GET',
  dataType: 'json',
  success: function(data) {
    console.log('success: ' + data);
  }
});

Do I need any changes in this one or is there something wrong? 我需要对此进行任何更改,还是有问题?

I found that the issue when I tested your script was simply a CORS related one; 我发现我测试你的脚本时的问题只是一个与CORS相关的问题; by appending CORS-anywhere API to the URL I was able to hit your endpoint with your exact same code. 通过将CORS-anywhere API附加到URL,我可以使用完全相同的代码命中您的端点。 Try the code below (just swap your API key) 尝试下面的代码(只需交换您的API密钥)

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
      <title>Ilan's Test</title>
   </head>
   <body>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
      <script>
         var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=by-chloe&location=boston";

         $.ajax({
            url: myurl,
            headers: {
             'Authorization':'Bearer xxxxxxxxxxxxxxxxxxxxxxx',
         },
            method: 'GET',
            dataType: 'json',
            success: function(data){
                console.log('success: '+data);
            }
         });      

      </script>
   </body>
</html>

// Edit -- Please see the code below for usage on how to use the values returned from the API. //编辑 - 请参阅下面的代码,了解如何使用API​​返回的值。

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
      <title>Ilan's Test</title>
   </head>
   <body>

   <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div id="results">

                </div>
            </div>
         </div>
   </div>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
      <script>
         var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=by-chloe&location=boston";

         $.ajax({
            url: myurl,
            headers: {
             'Authorization':'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
         },
            method: 'GET',
            dataType: 'json',
            success: function(data){
                // Grab the results from the API JSON return
                var totalresults = data.total;
                // If our results are greater than 0, continue
                if (totalresults > 0){
                    // Display a header on the page with the number of results
                    $('#results').append('<h5>We discovered ' + totalresults + ' results!</h5>');
                    // Itirate through the JSON array of 'businesses' which was returned by the API
                    $.each(data.businesses, function(i, item) {
                        // Store each business's object in a variable
                        var id = item.id;
                        var alias = item.alias;
                        var phone = item.display_phone;
                        var image = item.image_url;
                        var name = item.name;
                        var rating = item.rating;
                        var reviewcount = item.review_count;
                        var address = item.location.address1;
                        var city = item.location.city;
                        var state = item.location.state;
                        var zipcode = item.location.zip_code;
                        // Append our result into our page
                        $('#results').append('<div id="' + id + '" style="margin-top:50px;margin-bottom:50px;"><img src="' + image + '" style="width:200px;height:150px;"><br>We found <b>' + name + '</b> (' + alias + ')<br>Business ID: ' + id + '<br> Located at: ' + address + ' ' + city + ', ' + state + ' ' + zipcode + '<br>The phone number for this business is: ' + phone + '<br>This business has a rating of ' + rating + ' with ' + reviewcount + ' reviews.</div>');
                  });
                } else {
                    // If our results are 0; no businesses were returned by the JSON therefor we display on the page no results were found
                    $('#results').append('<h5>We discovered no results!</h5>');
                }
            }
         });      

      </script>
   </body>
</html>

Remember swap your API key to make the above example work. 请记住交换API密钥以使上述示例有效。

CORS is usually enabled server-side; CORS通常在服务器端启用; it's a way to prevent unauthorized domains from connecting to and getting data outside of what's allowed; 这是一种防止未经授权的域连接到允许的数据以外的数据的方法; I think if you whitelist the IP address of your server you may still run into issues; 我想如果你将服务器的IP地址列入白名单,你可能仍会遇到问题; I've built many projects which all required bypassing CORS (either using the CORS-Anywhere API, or by making a request asking for JSONP datatype). 我已经构建了许多项目,这些项目都需要绕过CORS(使用CORS-Anywhere API,或者发出请求JSONP数据类型的请求)。 Cors-Anywhere in general is an open-sourced API you can implement it on your own server or continue using it from the heroku URL; Cors-Anywhere通常是一个开源API,您可以在自己的服务器上实现它,或者继续使用heroku URL; either way you should be able to complete your project. 无论哪种方式,你都应该能够完成你的项目。

Please let me know if the above code sample worked for you; 如果以上代码示例适合您,请告诉我们; Thanks! 谢谢! - Ilan - 宜兰

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM