【问题标题】:Cannot access Zomato APIs JSON object无法访问 Zomato APIs JSON 对象
【发布时间】:2017-03-30 19:02:32
【问题描述】:

我正在 Udacity 的网络开发纳米学位课程中开展一个项目。我决定使用餐厅信息并生成我的 API 密钥。但是,当我在 AJAX 对象中使用它来获取数据时,开发工具会向我显示“无效 API”错误。不过,API 是正确的。请帮忙。

这是我的代码:

$(document).ready(function(){
$("button").click(function(){
    $.get("https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID", { "Accept": "application/json", "user-key": 'MY_API_KEY' }, function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

});

这是 Zomato 的文档:

卷曲:

curl -X GET --header "Accept: application/json" --header "user-key: MY_API" "https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID"

网址:

https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID

请注意,我使用的餐厅 ID 和 API 是正确的。我对PHP不太了解,所以不知道curl是什么意思。

【问题讨论】:

    标签: javascript json api curl zomato-api


    【解决方案1】:

    请尝试以下代码:

    $(document).ready(function(){
      $("button").click(function(){
        $.get("https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID&apikey=MY_API_KEY", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
      });
    });
    

    但是,由于安全问题,不鼓励使用上述方法。您可以通过在服务器端编写一个处理程序,使用 PHP 中的服务器到服务器调用来访问 Zomato API,该处理程序可以从按钮单击事件作为 ajax 调用进行调用。这是示例 PHP 处理程序:

    $curl_channel = curl_init('https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID&apikey=MY_API_KEY');
    curl_setopt($curl_channel, CURLOPT_RETURNTRANSFER, true);
    $curl_response = curl_exec($curl_channel);
    curl_close($curl_channel);
    //Convert output to object
    $curl_output = json_decode($curl_response);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2016-07-02
      • 1970-01-01
      • 2014-07-16
      • 2017-11-03
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多