问题描述
大家好,
让我们说清楚。在php中我使用了json_encode(...),然后在javascript中得到了值,看起来如下:
lets make this very clear. In php i used json_encode(...) and then got the value in javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
我想把它变成一个普通的javascript数组,如下所示:
And i would like to make this into a normal javascript array, like so:
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?
谢谢你
推荐答案
听起来你在JavaScript中检索一个JSON字符串(也许是通过AJAX?)。如果你需要将它变成一个实际的数组值,你可能想要使用 JSON.parse()
。
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()
.
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
如果你实际上是在页面中写出一个值,而不是使用AJAX,那么你应该能够直接回显 json_encode
的输出而不引用; JSON本身就是有效的JavaScript。
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_encode
directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
这篇关于Javascript将PHP Json转换为javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!