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

Javascript 无法使用jQuery.ajax()从Yelp API检索数据,javascript,jquery,ajax,Javascript,Jquery,Ajax,我试图使用jQuery.ajax方法从YelpAPI检索JSON数据,但它在控制台中没有显示任何内容 新的Yelp授权只需要发送头,如下所示: "Authorization": "Bearer <apikey>" 我是否需要对此脚本进行任何更改,或者是否有问题?我在测试您的脚本时发现问题只是与CORS相关的问题;通过将CORS anywhere API附加到URL,我能够用完全相同的代码访问您的端点。尝试下面的代码,只需交换API密钥 <!doctype html> &

我试图使用jQuery.ajax方法从YelpAPI检索JSON数据,但它在控制台中没有显示任何内容

新的Yelp授权只需要发送头,如下所示:

"Authorization": "Bearer <apikey>"

我是否需要对此脚本进行任何更改,或者是否有问题?

我在测试您的脚本时发现问题只是与CORS相关的问题;通过将CORS anywhere API附加到URL,我能够用完全相同的代码访问您的端点。尝试下面的代码,只需交换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>
//编辑-有关如何使用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>
记住交换API密钥以使上述示例正常工作

CORS通常在服务器端启用;这是一种防止未经授权的域连接到和获取超出允许范围的数据的方法;我认为如果你把服务器的IP地址列为白名单,你可能仍然会遇到问题;我已经构建了许多项目,它们都需要绕过CORS,要么使用CORS Anywhere API,要么请求JSONP数据类型。Cors Anywhere通常是一个开源API,您可以在自己的服务器上实现它,也可以从heroku URL继续使用它;无论哪种方式,你都应该能够完成你的项目

请让我知道,如果上述代码样本为您工作; 谢谢
-Ilan

嘿@Ilan p,它确实起了作用,我的控制台显示了成功和目标。我猜是json对象。你能进一步帮助我吗?我如何看待回复?我需要解析数据吗?除了使用代理之外,还有其他方法克服CORS吗?我一直在使用heroku代理时遇到请求过多的错误。所以我想知道是否有办法绕过它。像JSONP?Yelp的API没有为AJAX请求提供CORS解决方案,他们表示不支持解析,理想情况下,您可以尝试使用PHP将其卷曲,并将AJAX请求生成自己的API;我不确定您提出了多少请求,尽管根据我的经验,使用CORS代理的大多数解决方案是最好的。带填充数据类型的Jsonp Json:Jsonp返回401,这意味着他们也不允许它;当然,你最好还是选择CORSA或者试试服务器端语言。我现在明白了,也明白了。我了解科尔斯。谢谢你@IlanP我会继续和Corsa在一起。
<!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>