用JavaScript解析一个单独的PHP数组 [英] Parsing a Separate PHP Array in Javascript

查看:85
本文介绍了用JavaScript解析一个单独的PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,作为一种学习练习,我试图将我正在为某人编写的网站(用PHP,MySQL和CSS编写)移植到Ajax(具体来说,实际上,只是添加Javascript,以便该页面是动态的,而不需要不断地重新加载.)

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).

不幸的是,我有一些要保留为PHP的脚本(例如,给定受害者数组的用于更新数据库的脚本),因为我需要它与数据库进行交互,这意味着该数组必须保持PHP(我认为).

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).

因此,给定此文件

<?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"

);

?>

有没有一种方法可以使用Javascript提取值?

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

或者,考虑一下,将受害者列表存储为XML文件更好,这样PHP和Javascript都可以读取它吗?甚至,我将如何去做呢?

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?

推荐答案

阅读 JSON 并查看用于PHP5的 json_encode().

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

您可以将PHP数组转换为JSON,这是一个字符串.然后将该字符串打印到您的页面中,并与Javascript一起使用

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>

这对于返回Ajax请求的数据特别有用

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>

这篇关于用JavaScript解析一个单独的PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆