vue中ajax发送接收json总结
系统结构: 后端:python中tornado 前端:vue.js 主要问题:跨域问题和json收发 1、跨域问题(python中tornado中设置): 后端: 1>实现options方法 2>设置相关允许的头域 def set_default_headers(self): print "setting headers!!!" self.set_header("Access-Control-Allow-Origin","*") self.set_header("Access-Control-Allow-Credentials","true") self.set_header("Access-Control-Allow-Methods","*") self.set_header("Access-Control-Allow-Headers","x-requested-with,Content-Type,Access-Token") self.set_header("Access-Control-Expose-Headers","*") # self.set_header('Access-Control-Allow-Methods','POST,GET,OPTIONS') def options(self): # no body # self.set_default_headers() self.set_status(204) self.finish() 前端(vue): <script> export default{ name: 'xxxxxi',data () { return { selected: [],result: '' } },methods:{ queryResult: function () { var self = this; var sendData = {}; var selectedText = this.selected; sendData.names=selectedText var sendJson = JSON.stringify(sendData); this.$http({ method: 'post',url: 'http://localhost:8888/getSympton',crossDomain: true,data: sendJson }).then(response=> { var jsonData = JSON.stringify(response.data,null,4); this.result = jsonData; }).catch(function (error) { this.result = 'filed!!'; }.bind(self)); } } } </script> 2、注意: 1>vue使用axios发送http请求,对应的main.js设置如下:
import axios from
'
axios
'
import VueAxios from
'
vue-axios
'
Vue.prototype.$http
=
axiosVue.prototype.$ajax
=
axiosVue.use(VueAxios,axios)
queryResult在中发送使用this,另外进入请求作用域不同,需要设置到一个变量上,然后通过bind方法设置进去,否则的话会发送访问不到result对象 2>json解析 a)JSON.stringify(response.data,4)和JSON.stringify(object)方法 b)js中声明一个对象设置对应的属性,很方便的就完成了json的生成 3、遗留问题: 当前还没有使用vue的过滤器,后续学习 4、参考文章 ajax跨域,这应该是最全的解决方案了 https://segmentfault.com/a/1190000012469713 js中几种实用的跨域方法原理详解 https://www.cnblogs.com/2050/p/3191744.html 如何解决出现AXIOS的Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. http://www.cnblogs.com/caimuqing/p/6733405.html js操作json https://www.cnblogs.com/May-day/p/6841958.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |