【问题标题】:Storing a variable in ajax response as a global variable and use for sending other ajax requests?将 ajax 响应中的变量存储为全局变量并用于发送其他 ajax 请求?
【发布时间】:2018-06-03 20:10:37
【问题描述】:

我得到 ajax 响应

{ pid: 6, status: true }

我需要存储 pid 并在下一个 ajax 发布请求中传递它。

我目前的vue js如下

submitBox = new Vue({
  el: "#submitBox",
  data: {
    name: '',
    gstno: '',
    about: '',
    pid: '',
  },
  methods: {
    handelSubmit: function(e) {
      var vm = this;
      data = {};
      data['name'] = this.name;
      data['gstno'] = this.gstno;
      data['about'] = this.about;
      $.ajax({
        url: 'alpha/add/post/',
        data: data,
        type: "POST",
        dataType: 'json',
        success: function(e) {
          if (e.status) {
            alert(" Success")

          } else {
            vm.response = e;

            alert(" Failed")
          }
        }
      });
      return false;
    }
  },
});

我需要将pid 存储为全局变量,并为所有ajax 请求使用相同的变量。我怎样才能做到这一点?

【问题讨论】:

  • 当你说“存储”时,你的意思是把结果存储在Vue之外的某个地方吗??
  • vue 本身没有?如果能够在另一个 vue 中使用它会更好..
  • 哦...你最好使用Vue componentsVuex,如果你要存储的数据只会被其他Vues使用。

标签: javascript jquery vue.js vuejs2 vue-component


【解决方案1】:

小东西,如果你有一个小的应用程序并且没有太多的架构或js 只驻留在那个页面上,那么你可以使用全局变量

为这个小东西使用vuex是不可取的(如果他已经在使用它会很好)

当您收到 ajax 响应时,您可以全局设置 id

if (e.status) {
    window._postPid = e.pid; // assume `e` is response and e.pid is 6
}
else {
    // according to your need.
    // this is optional window._postPid = null;
}

现在你可以在任何你想使用的地方访问它

console.log(window._postPid); // 6

这不是大型应用程序的首选。因为我们不想破坏全局命名空间或冲突变量。

但它会做你想做的事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多