Npcink Blog
切换菜单

如何将 PHP 的变量传给 js?

在 vue 文件中,通过 axios 来远程调用 PHP 产出的内容。

本页目录4 节

在实际开发中,我们常常需要用到 PHP 产出的数据,通过 JS 调用来在前台处理。

方法一:内嵌法

在 php 文件里面写 JS 内容,直接传,案例如下:

<?php
//构造链接
$wx_url = "https://www.npc.ink/";
?>
<button onclick="openWeapp()">点击跳转小程序哦</button>
<script>
var urlscheme= "<?php echo $wx_url ?>";
function openWeapp() {
//window.alert(1);
location.href = urlscheme;
}
</script>

如您所见,这样并不优雅。

方法二:Axios 获取

php 输出数组,我们使用 Axios 远程获取即可。

新建 test.php 文件,输入以下代码

<?php
header('Content-Type:application/json');//加上这行,前端那边就不需要var result = $.parseJSON(data);
$retdata = array(
"student"=>array("name"=>"feiq","sex"=>"male","age"=>18,"job"=>'agineer'),"superstar"=>array("name"=>"MM","sex"=>"female","age"=>20,"job"=>'signer')
);
echo json_encode($retdata);
?>

新建 index.html,调用 PHP 的内容

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>从php文件中异步获取json数据</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="myphp">
<p>从php文件中读取json数据</p>
<ol>
<li>名字</li>
<li v-for="sites in info">{{sites.name}}</li>
</ol>
<ol>
<li>性别</li>
<li v-for="sites in info">{{sites.sex}}</li>
</ol>
<ol>
<li>年龄</li>
<li v-for="sites in info">{{sites.age}}</li>
</ol>
<ol>
<li>职业</li>
<li v-for="sites in info">{{sites.job}}</li>
</ol>
</div>
<script>
const App = Vue.createApp({
data() {
return {
info: [],
}
},
mounted() {
axios
.get('test.php')
.then(response => {
console.log(response);
this.info = response.data;
})
.catch(function (error) {
alert(error)
})
}
})
App.mount("#myphp")
</script>
</body>
</html>

其中的 test.php,一般长这样

https://www.npc.ink/test/test.php

注意

跨域问题涉嫌安全,请小心。

参考文章