簡體   English   中英

從 Curl 輸出 JSON APi 調用 Ajax

[英]Outputting JSON from Curl APi call to Ajax

我正在做一個課程項目,我需要使用 php 撥打 api 電話。

Ajax 調用如下所示:

$('#btnOneRun').click(function() {
    $.ajax({
        url: "libs/php/getCapitalSummary.php",
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.status.name == "ok") {
                console.log(result)
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown)
        }
    }); 
});

php api 調用如下所示:

<?php

    // remove for production

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);



    $url='http://api.geonames.org/wikipediaSearchJSON?formatted=true&q=london&maxRows=1&username=flightltd&style=full';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result, true);   

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];

    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 

?>

這非常有效。 我使用相同的例程對 go geonames API 進行了類似的調用,並且這樣做沒有任何問題,因為它們提供了返回的根 object 的名稱。 在上面的例子中,它被稱為 geonames

$output['data'] = $decode['geonames'];

我正在嘗試使用此模式調用 accuweather API。為此,我沒有根 object 的名稱。

我使用了上面的例程,將該特定代碼行更改為$output['data'] = $result; 瞧,我可以看到geonames的來源。

{
    "status": {
        "code": "200",
        "name": "ok",
        "description": "success",
        "returnedIn": "120 ms"
    },
    "data": "{\"geonames\": [{\n  \"summary\": \"London is the capital and most populous city of England and the United Kingdom. Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium (...)\",\n  \"elevation\": 8,\n  \"geoNameId\": 2643743,\n  \"feature\": \"city\",\n  \"lng\": -0.11832,\n  \"countryCode\": \"GB\",\n  \"rank\": 100,\n  \"thumbnailImg\": \"http://www.geonames.org/img/wikipedia/43000/thumb-42715-100.jpg\",\n  \"lang\": \"en\",\n  \"title\": \"London\",\n  \"lat\": 51.50939,\n  \"wikipediaUrl\": \"en.wikipedia.org/wiki/London\"\n}]}"
}

在這一點上,我想:“現在我只需要對 Accuweather 的 API 調用做同樣的事情,我將能夠找到我需要在$output['data'] = $decode['what_goes_here?'];上的大括號之間鍵入的內容$output['data'] = $decode['what_goes_here?'];但是當我嘗試這樣做時,JSON 返回值不像上面那樣顯示 object。

當直接從我的 javascript 文件或通過他們網站上的示例調用時,從 accuweather API 返回的 JSON 看起來像這樣:

[
  {
    "LocalObservationDateTime": "2022-03-10T06:47:00+00:00",
    "EpochTime": 1646894820,
    "WeatherText": "Light rain",
    "WeatherIcon": 12,
    "HasPrecipitation": true,
    "PrecipitationType": "Rain",
    "IsDayTime": true,
    "Temperature": {
      "Metric": {
        "Value": 8,
        "Unit": "C",
        "UnitType": 17
      },
      "Imperial": {
        "Value": 46,
        "Unit": "F",
        "UnitType": 18
      }
    },
    "MobileLink": "http://www.accuweather.com/en/gb/london/ec4a-2/current-weather/328328?lang=en-us",
    "Link": "http://www.accuweather.com/en/gb/london/ec4a-2/current-weather/328328?lang=en-us"
  }
]

我正在尋求兩件事之一的幫助:

a) 一種在不知道 object 名稱是什么的情況下解碼 JSON object 和 AJAX 調用的 output 的方法,或者;

b) 在 javascript 上接收解碼后的 object 並對其進行解碼以訪問其屬性。

我非常感謝你。

編輯:我更多地研究了 PHP 並意識到我不明白 php 例程只是使用括號表示法訪問解碼后的 object 的屬性: $decode['geonames']

我繼續研究它並意識到我可以在我的 javascript 文件中使用JSON.parse()

所以我將 php 文件中的特定代碼行更改為$output['data'] = $result;

然后在我的 ajax 調用中,我可以訪問使用調用JSON.parse(result.data)后返回的 JSON 的屬性,如下所示:

$('#btnOneRun').click(function() {
    $.ajax({
        url: "libs/php/getWeather.php",
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.status.name == "ok") {
        console.log(JSON.parse(result.data))
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown)
        }
    }); 
});

這被記錄為:

[
    {
        "LocalObservationDateTime": "2022-03-10T08:13:00+00:00",
        "EpochTime": 1646899980,
        "WeatherText": "Mostly cloudy",
        "WeatherIcon": 6,
        "HasPrecipitation": false,
        "PrecipitationType": null,
        "IsDayTime": true,
        "Temperature": {
            "Metric": {
                "Value": 9.1,
                "Unit": "C",
                "UnitType": 17
            },
            "Imperial": {
                "Value": 48,
                "Unit": "F",
                "UnitType": 18
            }
        },
        "MobileLink": "http://www.accuweather.com/en/gb/london/ec4a-2/current-weather/328328?lang=en-us",
        "Link": "http://www.accuweather.com/en/gb/london/ec4a-2/current-weather/328328?lang=en-us"
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM