简体   繁体   中英

Storing a variable in ajax response as a global variable and use for sending other ajax requests?

I am getting ajax response as

{ pid: 6, status: true }

I need to store pid and pass it in the next ajax post request.

My current vue js is as follows

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;
    }
  },
});

I need to store pid as a global variable and use the same for all the ajax requests. How can I achieve this?

small thing, if you have small application and there is not much architecture or js is resides on that page only then you can use global variable

using vuex for just this little thing is not suggestible (it will be good if he is already using it)

when you get back ajax response then you can set id globally

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;
}

now you can access it anywhere you want using

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

this is not preferred for large scale app. as we dont want to spoil global namespace or conflict variables.

but it will do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM