为了账号安全,请及时绑定邮箱和手机立即绑定

Json 返回 [object object] 而不是值

Json 返回 [object object] 而不是值

PHP
侃侃无极 2023-04-02 10:20:22
我正在尝试提取 json 的值,但是当我返回它时,我得到了一个对象对象。我在解码时做错了什么?这是php中的解码代码<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");$info = json_decode($contenido,true);   $cadena=array(        0=>$info['cotizacion'],    );    echo json_encode($cadena);      ?> 这是功能代码<script>    $(function() {        $("#btnbuscar").on('click',function(){                     var direccion='servicio.php';            $.ajax({                type:'get',                url:direccion,                success:function(datos){                    var campo=eval(datos);                    alert(datos[0]);            }            });            return false;        });    });</script>
查看完整描述

4 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

有几种解决方案,但在调用 json 链时不要在javascript/jquery中出错。


例如:


<?php

// Page : service.php

$json = '{

    "service": "Reference dollar exchange rate",

    "website": "website.com",

    "link": "https://www.website.com/gearbox_type/",

    "quotation": [{

        "buy": 3.419,

        "sale": 3.424

    }]

}';

// $json = file_get_contents("https://www.website.com/api/example.json");

$info = json_decode($json,true); // convert array

$cadena=array(

    0=>$info['quotation'][0],

);

echo json_encode($cadena); // convert json

// get-> [{"buy":3.419,"sale":3.424}]

echo json_encode($cadena[0]); // convert json

// get-> {"buy":3.419,"sale":3.424}

?>


// Javascript 

// To better use your function I would have to do a cleanup of the code with JSON.parse

<script>

    $(function() {


        /*

         * Check yes and Json and convert json string

         * Analyze the data with JSON.parse () and the data becomes a JavaScript object.

         * Ex. var obj = '{hello:'mitico'}' -> convert object

         * $.clean_string_json(obj) return-> {hello:'mitico'}

         * $.clean_string_json('text' + obj) return-> {}

         * $.clean_string_json('text' + obj,false) return-> false

         * $.clean_string_json('text' + obj,true) return-> true

         */

        $.clean_string_json = function (str,xreturn) {

            try {

                return JSON.parse(str);

            } catch (e) {

                return xreturn === false ? false : xreturn || {};

            }

        };


        $("#btnbuscar").on('click',function(){          

            $.ajax({

                type:'get',

                url: 'service.php',

                success:function(datos){

                    var campo= $.clean_string_json(datos);

                    alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}

                }

            });

            return false;

        });

    });

</script>


查看完整回答
反对 回复 2023-04-02
?
largeQ

TA贡献2039条经验 获得超7个赞

欢迎来到计算器!我们希望您喜欢这里。


正如@Anurag Srivastava 已经指出的那样,直接调用 url,你会得到 json,你不需要代理。


const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";

$.get(jUrl)

.then(({cotizacion}) => console.log(cotizacion));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


查看完整回答
反对 回复 2023-04-02
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

当你这样写的时候:


$cadena=array(

    0=>$info['cotizacion'],

);

echo json_encode($cadena);

你的 $info 是一个数组,cadena 也是一个数组。所以你可以像这样将 $cadenra 指向数组:


$cadena= $info['cotizacion'];

echo json_encode($cadena);

或者像这样修复你的js:


alert(datos[0][0]);


查看完整回答
反对 回复 2023-04-02
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

这是一种无需 Ajax 但使用的简单读取 JSON 的方法$.getJSON


在您的 PHP 文件中,因为您只想获得“cotizacion”数据更改:$cadena=array(0=>$info['cotizacion']如果$cadena=array(0=>$info['cotizacion'][0]您计划拥有并循环多个“cotizacion”,则可以删除 [0]


在你的 javascript 上使用:


$.getJSON("servicio.php", function(data) {

  var items = [];

  $.each(data[0], function(key, val) {

    (key + '=' + val);

  });

});


查看完整回答
反对 回复 2023-04-02
  • 4 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信