【问题标题】:How do I access JSON encoded array in php如何在 php 中访问 JSON 编码的数组
【发布时间】:2014-10-30 16:53:49
【问题描述】:

假设我有这个。

$myArray = array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );

然后我对其进行编码,

$bar = json_encode($myArray);

现在,如果我将 echo $bar; 传递回 ajax,我可以像这样访问每个数组对象。

success: function(data)
         { 
            var name = data.name;
            var platform= data.platform;

如何在 php 中访问每一个在 JSON 中编码后的内容?

【问题讨论】:

  • 只需访问您构建它的数组$myArray,或者如果您正在谈论处理后续请求中发送的JSON,只需json_decode()即可。
  • 您不访问 json 编码的数据。 json 是一种传输/通信格式。您将其解码回本机数据结构,然后访问它。

标签: php arrays ajax json


【解决方案1】:
$bar=json_decode($bar, true); 
print_r($bar);

【讨论】:

    【解决方案2】:

    请检查下面的代码 (index.php),它最终运行良好。我相信您需要先解析 JSON,然后才能在 ajax 成功函数中获取数据。

    <?php
    if($_GET){
    $myArray = array(
        'userAgent' => "FF",
        'name'      => "Asik",
        'version'   => "1.0",
        'platform'  => "Windows",
        'pattern'    => ""
    );
    
    echo json_encode($myArray);
    exit;
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $.ajax({url:"index.php?getResponse=true",success:function(result){
          result = JSON.parse(result);
          $("#div1").html(result.name);
        }});
      });
    });
    </script>
    </head>
    <body>
    
    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
    <button>Get External Content</button>
    
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 2019-02-18
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多