[英]How do I get values from a PHP array to a Javascript Array?
So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. 因此,我目前正在为某个外部家庭的网站做一些编码,不得不创建一个条形图,现在我需要用他们的SQL数据库中的数据填充它。 First I just echo'd the array like this:
首先,我只是像这样回应数组:
PHP: PHP:
<?php
$exampleArray = ["212", "33", "7"]
?>
and JS: 和JS:
<script> var jExampleArray = <? echo json_encode($exampleArray);?>; </script>
And then I used jExampleArray in my bar chart code. 然后我在条形图代码中使用了jExampleArray。 Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page.
现在我很高兴,但是他们说它需要更安全(涉及他们的公司),我必须找到一种方法来确保在浏览页面代码时没有人能看到数据。 I thought about using Ajax and what not but it just didn't work for me.
我考虑过使用Ajax,什么也没用,但是对我来说不起作用。 I got it to alert me the array, but was not able to fill a Javascript array with it.
我得到它来提醒我该数组,但无法用它填充Javascript数组。
I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. 我以前从没做过JS,PHP或SQL的工作,只在学校学习过Java,所以我一无所知,我做的大部分工作都是借助互联网。 Luckily I managed to at least understand the code I wrote/copied.
幸运的是,我至少了解了我编写/复制的代码。
Edit: [] for a JS array not {} 编辑:[]用于JS数组而不是{}
Your syntax for creating the PHP array is incorrect. 您创建PHP数组的语法不正确。
Use the function json_encode
to transform PHP arrays into Javascript arrays and objects. 使用函数
json_encode
将PHP数组转换为Javascript数组和对象。
<?php
$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];
echo 'var Array = ' . json_encode($arr) . PHP_EOL .
'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;
Will result in the following: 将导致以下结果:
var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}
Some pseudo code to show how you might accomplish the stated goal 一些伪代码说明如何实现既定目标
$data=array();
while( $rs=$db->fetch() ){
$data[]=array(
'field_1' => $rs->field_1,
'field_2' => $rs->field_2,
'field_3' => $rs->field_3
);
}
$json=json_encode( $data );
<script>
<?php
echo "var jExampleArray={$json};";
?>
/* rest of barchart code */
</script>
If the PHP array is available at page load use: 如果页面加载时可以使用PHP数组,请使用:
<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>
To retrieve PHP array in JS after page load using ajax: 要使用ajax在页面加载后在JS中检索PHP数组:
var arr = JSON.parse(responseArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.