【问题标题】:Returning API as Object with PHP/JS使用 PHP/JS 将 API 作为对象返回
【发布时间】:2021-08-09 19:11:21
【问题描述】:

我将 PHP 请求作为数组返回:

JS:

$('#btnRun1').click(function() {

    $.ajax({
        url: "source/php/getCityDetails.php",
        type: 'POST',
        dataType: 'json',
        data: {
            q: $('#selCity').val()
            },
        success: function(result) {

            console.log(JSON.stringify(result));

            if (result.status.name == "ok") {

                $('#txtCityName').html(result['data'][0]['toponymName']);
                $('#txtLat').html(result['data'][0]['lat']);
                $('#txtLong').html(result['data'][0]['lng']);
                $('#txtId').html(result['data'][0]['Id']);
    
                                    
            }
        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // TBC
        }
    });
});

PHP:

<?php

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

$executionStartTime = microtime(true);



$url='http://covered/searchJSON?formatted=true&q=' . $_REQUEST['q'] . '&maxRows=1&lang=en&username=covered';


$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['covered'];



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

echo json_encode($output); 
?>

这按预期工作,接受请求并将其发布到 HTML。

我需要对作为对象而不是数组返回的另一个 API 请求执行相同的操作。我不知道如何重新编码这些 '$('#txtCityName').html(result['data'][0]['toponymName']);'这样做。

有没有人可以帮助或指出我可以解决的方向?我在 Stackoverflow 或 Google 上找不到任何我可以理解或实施的解决方案。

编辑:添加示例

【问题讨论】:

  • 到目前为止你尝试过什么?你被困在哪里了? 究竟是什么不适用于给定的代码?
  • 当 API 请求为数组时,该代码有效。 IE。返回like: 数组名(0: details, details, details 1: 0: details, details, details 2: 0: details, details, details) 但是当返回的是对象时: 对象名( details) 代码不起作用因为它正在寻找一个数组。
  • 取决于对象的外观,但总的来说我认为result.data.[0].toponymName
  • 编辑:将图片添加到原始帖子 $('#txtCityName').html(result['data'][0]['toponymName']);适用于数组,但我不知道如何将其更改为使用对象。
  • $decode['covered'] 是一个数组,如果你想要 result.data.toponymName$output['data'] = $decode['covered'][0]; 代替(显然先检查它的集合)

标签: javascript php arrays api object


【解决方案1】:

感谢 AbraCadaver!

变化:

$('#txtCityName').html(result['data'][0]['toponymName']);

收件人:

$('#txtCityName').html(result.data.toponymName);

正是我要返回的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多