有三种方法可从 PHP 获取 JavaScript 数组:将数组编码为 JSON 并使用 JSON.parse() 解析,使用 Axios 库发送请求并解析响应,或使用文件包含并在 JavaScript 中包含文件。
如何使用 JavaScript 获取 PHP 数组
方法一:使用 PHP 服务端将数组编码为 JSON
步骤:
$array = [1, 2, 3]; echo json_encode($array);
const json = '{"1":2,"2":3,"3":4}'; // 接收到的 JSON 字符串 const array = JSON.parse(json); console.log(array); // [1, 2, 3]
方法二:使用 Axios 库(仅限前端)
立即学习“PHP免费学习笔记(深入)”;
步骤:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios.get('script.php') .then(response => { const array = response.data; console.log(array); // [1, 2, 3] });
方法三:使用 PHP 文件包含(仅限后端)
步骤:
$array = [1, 2, 3]; file_put_contents('array.json', json_encode($array));
const array = require('./array.json'); console.log(array); // [1, 2, 3]
以上就是js如何获取php数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号