dpus81500574 2012-03-30 13:39
浏览 24
已采纳

如何将PHP数组转码为JSON数组?

UPDATE: Based on suggestions here, I've modified my code. To get a handle on how this works, I am only trying to alert the PHP array with JSON. Still cannot get it to work. The code below resides on the same test.php page. If refreshed, should the alert fire? The function seems to fail as well. The TEST alert does not work.

<?php
  header('Content-type: application/json');
  $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
  echo json_encode($arr);
?>

<script type="text/javascript">
  $(function() {
    $.getJSON('test.php',function(data) {
      alert("TEST");

      $.each(data, function(key, item) {
        alert(key + item); }); 
      });
    });
  });
</script>

I am new to JSON and trying to get a PHP array to display in an HTML file. Below is a simple example. Please tell me if this should work and what I am doing wrong. I am trying to output the keys in this array. Thanks.

My PHP script (test.php):

     $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
json_encode($arr);

$content = file_get_contents('test.htm');
echo $content;

My HTML page (test.htm):

<script type="text/javascript">

  $(function() {
$.getJSON('test.php',function(data) {
  $.each(data,function(i, item) {
    alert(item.key);
      });
   });
});

 </script>
  • 写回答

7条回答 默认 最新

  • dongse3348 2012-03-30 13:49
    关注

    Make sure you have included jQuery in your HTML file.

    As you are only alerting keys, you don't have to wait for a dom-ready event - and even if you wanted to, I would first get the JSON and put the $(function... into the ajax callback.

    Your JSON-encoded PHP-array should look like this:

    {"item1":"test1","item2":"test2","item3":"test3"}
    

    Check about this in your debugger, or load test.php directly in your browser. As others have suggested, your PHP code with the file_get_contents is a bit odd.

    Last, your object traversal won't work. Look at the docs:

    $.each(data, function(key, item) {
        alert(key + item);
    });
    

    The string concatenator in JavaScript is the +, not the . as in PHP. item.key would try to access the key property of one of your items - none has such one as thy are strings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染