https://www.cnblogs.com/creazybeauty/p/8569043.html
Vue之使用ajax获取json数据,并用v-for循环显示在表格中
运行的时候,出现了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"
}]

本文详细介绍了如何在Vue项目中通过AJAX跨域获取JSON数据,并利用v-for指令将数据循环显示在HTML表格中。解决了跨域问题,并展示了完整的HTML、CSS、JavaScript代码及PHP后端实现。
3094

被折叠的 条评论
为什么被折叠?



