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, null, 4)和JSON.stringify(object)方法

b)js中声明一个对象设置对应的属性,很方便的就完成了json的生成

 

3、遗留问题:

当前还没有使用vue的过滤器,后续学习


4、参考文章

ajax跨域,这应该是最全的解决方案了 https://segmentfault.com/a/1190000012469713
前端AJAX请求跨域时遇到的一些坑 https://icewing.cc/post/about-cross-origin.html

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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小她爹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值