我正在做一個課程專案,我需要使用 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);
?>
這完美地作業。我已經使用相同的例程對 geonames API 進行了類似的呼叫,并且這樣做沒有問題,因為它們提供了回傳的根物件的名稱。在上面的例子中,它被稱為地名
$output['data'] = $decode['geonames'];
我正在嘗試使用這種模式來呼叫 accuweather API。然而,為此,我沒有根物件的名稱。
我使用了上面的例程,將特定的代碼行更改為$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}]}"
}
At this point I thought: "Now I just need to do the same with the API call to Accuweather and I will be able to find what I need to type between the curly brackets on $output['data'] = $decode['what_goes_here?']; but when I tried that, the JSON return does not display an object like the one above.
The JSON returned from the accuweather API when called straight from my javascript file, or through the example in their website, looks like this:
[
{
"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"
}
]
I am asking for help with one of two things:
a) A way to decode that JSON object without knowing what that object name is and output that to the AJAX call, or;
b) Receive the decoded object on javascript and decode it to access its properties there.
I immensely thank you in advance.
uj5u.com熱心網友回復:
編輯:我更深入地研究了 PHP,并意識到我不明白 php 例程只是使用括號符號來訪問解碼物件的屬性:$decode['geonames'].
我繼續研究它并意識到我可以JSON.parse()在我的 javascript 檔案中使用它。
所以我將 php 檔案中的特定代碼行更改為$output['data'] = $result;
然后在我的 ajax 呼叫中,我可以訪問使用呼叫后回傳的 JSON 的屬性,JSON.parse(result.data)如下所示:
$('#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"
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442084.html
標籤:javascript jquery json api curl
