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 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入