HTML代码
将以下内容保存为x.htm,并且上传到服务器如http://blog.uhaka.com/x.htm
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>JSON取数测试</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="main">
<table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>type</td>
<td>location</td>
</tr>
<tr v-for="r in rows">
<td>{{r.id}}</td>
<td>{{r.name}}</td>
<td>{{r.type}}</td>
<td>{{r.location}}</td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function () {
$.getJSON("https://你的地址.com/x.json", function (result, status) {
var v = new Vue({
el: '#main',
data: {
rows: result
}
})
});
});
</script>
</html>
远程json接口内容
- 保存以下内容,以flask为例。
- 注意添加cors白名单,譬如前面htm在x.com,那么对应的cors添加x.com到信任白名单,否则取不到数据。
- flask可能需要安装flask-cors
pip install flask-cors
- flask开启一个Json代码
```python
coding:utf-8
from flask import Flask,request from flask import Blueprint from flask_cors import *app = Blueprint(‘x’,name,subdomain=’x’)
app = Flask(name)
此处注意orgins后面添加白名单,不能设置成允许*,会有json劫持漏洞。
cors = CORS(app, resources={r”/*”: {“origins”: “http://blog.uhaka.com"}})
@app.before_request def before_request(): if request.url.startswith(‘http://‘): url = request.url.replace(‘http://‘, ‘https://‘, 1) return redirect(url, code=301)
@app.route(“/“) def index(): return “hello,ming”
@app.route(“/x.json”) def hello():
# 理应从数据库里查询,然后使用类似fastjson包装成json输出。
# 这里写成静态的作为Demo。
strs = '[{"id":1,"name":"张三","type":"工业","location":"市局"},{"id":2,"name":"李四","type":"工业","location":"市局"}]'
return strs
if name == ‘main‘:
#app = Flask(__name__)
app.config['SERVER_NAME'] ='x.com'
app.run(host='0.0.0.0',port=443,ssl_context=('你的证书路径.pem', '你的证书路径.key'))
```