简体   繁体   English

如何将数组值从PHP传递到JavaScript

[英]How to pass array values from PHP to JavaScript

I have a PHP array here: 我在这里有一个PHP数组:

$newArray = array(4,27,34,52,54,59,61,68,78,82,85,87,91,93,100);

I want this PHP array to be passed on to my JavaScript code to make my 'data' variable in my JavaScript the same as the array I declared on my PHP script. 我希望将此PHP数组传递给我的JavaScript代码,以使我的JavaScript中的“数据”变量与我在PHP脚本中声明的数组相同。 Here is my JavaScript code: 这是我的JavaScript代码:

<script type="text/javascript">
$(function() {

    data:  [4,27,34,52,54,59,61,68,78,82,85,87,91,93,100];

});
</script>

My idea is just embed the $newArray directly like this: 我的想法是像这样直接嵌入$ newArray:

data: <?php $newArray ?>

But it doesn't work. 但这是行不通的。 How would I do it? 我该怎么办? Thank you for your help. 谢谢您的帮助。

Just doing 只是做

data: <?php $newArray ?>

wouldn't output the contents of $newArray, you'd still need to output as well, by doing either 不会输出$ newArray的内容,您仍然需要通过执行以下任一操作来输出

echo $newArray
print $newArray

(Try that and you'll get a different error ;)) But even then, it won't be in the format that you want, so you'll want to use json_encode encode on it to format in a way that javascript can read it, like so (尝试这样做,您会得到一个不同的错误;)。但是即使那样,它也不会采用您想要的格式,因此您将希望使用json_encode编码对其进行格式化,从而使javascript可以读取像这样

data: <?php echo json_encode($newArray) ?>;

Use PHP's built in json_encode() function like this: 使用PHP内置的json_encode()函数,如下所示:

$array = array("item_1" => 1, "item_2"=> 2);
$json = json_encode($array);

Then pass that array to your JavaScript (via AJAX or some other method) and decode with the jQuery function $.parseJSON() like this: 然后将该数组传递给您的JavaScript(通过AJAX或其他方法),并使用jQuery函数$ .parseJSON()进行解码,如下所示:

$(function(){
    var json = $.parseJSON(passedFromPHP);
});

This will give you a JSON object that you can manipulate with JavaScript. 这将为您提供一个可以使用JavaScript处理的JSON对象。

您也可以这样做:

data: [<?php echo implode(',', $newArray); ?>];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM