在實際開發(fā)中,我們常常需要用到PHP產(chǎn)出的數(shù)據(jù),通過JS調(diào)用來在前臺處理。
方法一:內(nèi)嵌法
在php文件里面寫JS內(nèi)容,直接傳,案例如下:
<?php
//構造鏈接
$wx_url = "http://www.kartiktrivedi.com/";
?>
<button onclick="openWeapp()">點擊跳轉(zhuǎn)小程序哦</button>
<script>
var urlscheme= "<?php echo $wx_url ?>";
function openWeapp() {
//window.alert(1);
location.href = urlscheme;
}
</script>
如您所見,這樣并不優(yōu)雅。
方法二:Axios獲取
php輸出數(shù)組,我們使用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,調(diào)用PHP的內(nèi)容
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>從php文件中異步獲取json數(shù)據(jù)</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數(shù)據(jù)</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>職業(yè)</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,一般長這樣
http://www.kartiktrivedi.com/test/test.php
注意
跨域問題涉嫌安全,請小心。