简体   繁体   English

在ajax成功函数之外使用变量

[英]Use variable outside of ajax success function

I have a set of time out functions inside one function 我在一个函数中有一组超时函数

function myFunction()
{
   var data;

   setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(data) {
            var data = data.trim();
            // I want to be able to use this later on.
         }
       }):
   }, 6000);

   setTimeout(function(){
      var shipping = 'f_name='+f_name+data;
      // Append data from previous call to shipping
   }, 12000);
}

I'm wanting to retrieve the data from the ajax success function and then use it inside the next timeout function by appending it to the shipping variable. 我想从ajax成功函数中检索数据,然后在下一个超时函数中使用它,将它附加到运输变量。 I have declared the variable data outside of all the functions and then tried to add the success data to it. 我已经在所有函数之外声明了变量数据,然后尝试将成功数据添加到它。 When I alert out the shipping variable it doesn't show anything extra (what the data should be adding). 当我提醒出货变量时,它没有显示任何额外的数据(数据应该添加什么)。

The data is returning because I can see it in Google Chromes Network Tab. 数据正在返回,因为我可以在Google Chromes Network标签中看到它。

How can I set a variable to be used throughout the entire function!?!?!?!? 如何设置要在整个函数中使用的变量!?!?!?!?

Thank you in advance. 先感谢您。

Also, the success function is returning prior to the call for the data to be added because of the timeout functions. 此外,由于超时功能,在调用之前返回成功函数以添加数据。 I played with them to be set right for this instance. 我和他们一起玩这个例子。

As a bad way: up your var data; 作为一种坏方法:提高你的var data; and change var data = data.trim(); 并更改var data = data.trim(); to tdata = data.trim(); to tdata = data.trim(); from the function: 从功能:

var tdata;
function myFunction(){

    setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(data) {
            tdata = data.trim();
            // I want to be able to use this later on.
         }
       }):
    }, 6000);

    setTimeout(function(){
        var shipping = 'f_name='+f_name+tdata;
        // Append data from previous call to shipping
       }, 12000);

} }

使用全局变量的另一个名称,如global_data并在ajax中使用global_data = data.trim()分配数据值

function myFunction()
{
   var data;

   setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(resp) {
            data = resp.trim(); // Dont declare it inside
            // I want to be able to use this later on.
         }
       }):
   }, 6000);

   setTimeout(function(){
      var shipping = 'f_name='+f_name+data;
      // Append data from previous call to shipping
   }, 12000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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