運行的時候,出現了php跨域問題,解決辦法是在php的頭文件中添加了如下代碼:
header('Content-Type: application/json');
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:*');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
目的:在vue中獲取從ajax獲取的json數據,並用v-for循環顯示在表格中
效果如下:

html示例代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vue.js"></script> <script src="jquery.min.js"></script> <style> * { padding: 0; margin: 0; } table { margin: 100px auto; border: 1px solid #000; border-collapse: collapse; /*設置表格的邊框是否被合並為一個單一的邊框*/ border-spacing: 0; /*設置相鄰單元格的邊框間的距離*/ } tr { width: 300px; height: 50px; line-height: 50px; border-bottom: 1px solid #000; background-color: pink; } td, th { width: 99px; height: 50px; line-height: 50px; text-align: center; border-right: 1px solid #000; } </style> </head> <body> <div id="app"> <table> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>住址</th> </tr> </thead> <tbody> <tr v-for="site in sites"> <td v-text="site.name"></td> <td v-text="site.age"></td> <td v-text="site.address"></td> </tr> </tbody> </table> </div> </body> </html> <script> new Vue({ el: '#app', data: { sites: [] }, created: function () {
//為了在內部函數能使用外部函數的this對象,要給它賦值了一個名叫self的變量。 var self = this; $.ajax({ url: '/tablev-for.php', type: 'get', data: {}, dataType: 'json' }).then(function (res) { console.log(res);
//把從json獲取的數據賦值給數組 self.sites = res; }).fail(function () { console.log('失敗'); }) } }) </script>
php代碼如下:
<?php header('Content-Type: application/json'); header('Content-Type: text/html;charset=utf-8'); header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:*'); header('Access-Control-Allow-Headers:x-requested-with,content-type'); echo file_get_contents('tablejson.json');
json代碼示例如下:
[{
"name":"baby",
"age":27,
"address":"china weifang"
},
{
"name":"黃曉明",
"age":30,
"address":"china yantai"
},
{
"name":"鹿晗",
"age":22,
"address":"china qingdao"
}]
