简体   繁体   中英

jQuery Passing Variable from From One Function to Another Function

I need to create a variable and assign a value to this variable to use later on. To save complexity and keep it simple, I've removed details that are also part of what else goes into var item2. The variable in this example would be mySeries

var mySeries;

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
//Stuff happens here

//NEED TO ASSIGN VALUE TO mySeries HERE:
mySeries = item[0].series_id;

//Stuff happens here
});

//NEED TO USER mySeries VALUE HERE BUT IT IS NOT DEFINED
var item2 = mySeries;

With ajax you need to use callbacks since ajax is asynchronous :

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
   var mySeries;
   //Stuff happens here

   //NEED TO ASSIGN VALUE TO mySeries HERE:
   mySeries = item[0].series_id;
   save_series(mySeries)
   //Stuff happens here
});

function save_series(s){

   var item2 = mySeries;

   //...etc
}

在json请求完成后,mySeries get被分配,你的item2在完成之前被分配。

Yeah I think you need a setter for the item2 since it's happening after the function but since it's asynchronous it's not going to have a value until it returns. You could also use .ajax() and set the function to synchronous if you need that kind of functionality.

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