简体   繁体   中英

jquery having issue with global variable inside function ajax function

Following is the code:

var ret;
function fetch_data(param1){
  $.post(param1,
        function(data){
          if (data){
            ret = data*2;
            console.log("data", ret);
          }
          else{
            ret = 15;
            console.log("no data")
          }
        });
  return ret;
}

function hello(){
  ret = fetch_data("/post_data");
  console.log("from the main function", ret);
}

The above is a simplified schema of how i am working with things. i make a post request to a url and try to get the value, based on the returned value i manipulate the value and try returning it back to the function. The console.log shows a value inside the fetch_data function, but not within the hello function. Meaning no value is returned. Where am i getting it wrong?

After your javascript makes the initial ajax call the execution of the script proceeds to the return statement. At this point the response to your request has not been returned yet, therefore your callback function has not executed, meaning ret has not been assigned a value. You need to include the call to hello within your callback function in order to guarantee that ret has been assigned a value.

  var ret;
    function fetch_data(param1){
      $.post(param1,
            function(data){
              if (data){
                ret = data*2;
                console.log("data", ret);
              }
              else{
                ret = 15;
                console.log("no data")
              }
              hello();
            });
    }

function hello(){
  ret = fetch_data("/post_data");
  console.log("from the main function", ret);
}

There are two ways that Ajax can access the server. These are synchronous (wnere the script stops and waits for the server to send back a reply before continuing) and asynchronous (where the script allows the page to continue to be processed and will handle the reply if and when it arrives). Your function is performing asynchromnously, meaning the fetch_data function is executing the return statement before the ajax call is completed.

Order of Events:

  1. fetch_data is called
  2. fetch_data fires off ajax request.
  3. fetch data returns ret(undefined)
  4. hello function prints ret to console
  5. ajax response is received from server
  6. ret is assigned a value based upon ajax response

I would like to further suggest that you modify your code to what I consider to be a better approach. I believe this approach captures your intent better than specifying the hello function within your callback.

    function fetch_data(param1,callback){
      $.post(param1,
            function(data){
              callback(data);
            });
    }

function hello(data){
    if (data){
       ret = data*2;
       console.log("data", ret);
     }
     else{
       ret = 15;
       console.log("no data")
     }
  console.log("from the main function", ret);
}

function hello2(data){
  //...different logic that modifies data
  console.log("from the main function", ret);
}

//Function call passing the hello function as a parameter
fetch_data('/post_data', hello);

//Function call that passes hello2 function as a parameter
fetch_data('/post_data', hello2);

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