douju6542 2010-08-26 13:41
浏览 37
已采纳

在Javascript中解析单独的PHP数组

So, as sort of an exercise in learning, I am trying to port a site I was working on for someone, written in PHP, MySQL and CSS, over to Ajax (Specifically, really, just adding Javascript so that the page is dynamic instead of needing to constantly reload).

Unfortunately, I have some scripts I'd like to keep as PHP (for instance, a script to update a database given an array of victims) because I need it to interact with a database, and this means that the array must stay as PHP (I think).

So, given this file,

<?php

$victims = array(

    // Animals
    "chickens",
    "horses",
    "cows",

    // Supernatural
    "werewolves",
    "zombies",
    "vampires",
    "phantoms",

    // Human
    "U.S. Congressmen",
    "performance artists",

    // Inanimate, non-mechanical
    "pieces of fencepost",
    "barnhouses",

    // Mechanical
    "robots",
    "cyborgs"

);

?>

is there a way to reach into that file using Javascript an extract a value?

Or, come to think of it, would it be better to store the list of victims as an XML file so both the PHP and Javascript can read it? Or even, how would I go about doing that?

  • 写回答

1条回答 默认 最新

  • douao3063 2010-08-26 13:43
    关注

    Read up JSON and check out json_encode() for PHP5.

    You can convert a PHP array into JSON, this is a string. Then print that string out into your page and use it with your Javascript

    <script>
         var jsonarray = <?php echo json_encode($array); ?>;
         // now you can use jsonarray in your javascript
    </script>
    

    This is especially useful when returning data for an Ajax request

    <script>
         var jsonarray = <?php echo json_encode(array("status" => "success", "message" => "Something was completed OK")); ?>;
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里