Javascript 将 PHP Json 转换成 javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13994858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:22:05  来源:igfitidea点击:

Javascript Convert PHP Json into a javascript array

phpjavascriptjson

提问by Miguel P

So hi guys,

嗨,伙计们,

lets make this very clear. In php i used json_encode(...) and then got the value in javascript, looks as the following:

让我们说得很清楚。在 php 中,我使用了 json_encode(...) 然后在 javascript 中得到了值,如下所示:

["float","float","float","float"]  // PS: This is a string...

And i would like to make this into a normal javascript array, like so:

我想把它变成一个普通的 javascript 数组,像这样:

Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float

And now I'm asking you, how is this possible?

现在我问你,这怎么可能?

Thank You

谢谢你

回答by Amber

It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().

听起来您正在 JavaScript 中检索 JSON 字符串(也许通过 AJAX?)。如果你需要把它变成一个实际的数组值,你可能想要使用JSON.parse().

var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);

If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encodedirectly, without quoting; JSON itself is valid JavaScript.

如果您实际上是在页面中写出一个值,而不是使用 AJAX,那么您应该能够简单地直接回显 的输出json_encode,而无需引用;JSON 本身是有效的 JavaScript。

var myArray = <?php echo json_encode($myPhpArray); ?>;

回答by Brad Christie

var myArray = <?= json_encode($myPhpArray); ?>;

Pretty simple. ;-)

很简单。;-)

Example:

例子:

<?php
  $myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
  var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>

Should output (view-source):

应该输出(查看源代码):

<script type="javascript">
  var myJsArray = ["foo","bar","baz"];
</script>

Example

例子

回答by ballsDeep

I reccomend using jquery. The php file should look as such ...

我推荐使用 jquery。php 文件应该是这样的......

//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>

Then the jquery script ...

然后jquery脚本...

<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>