简体   繁体   中英

How can I start using variable outside $.get() function?

var userIdD = $.get('http://someurl.com/options.php', function(abc) {
  var abc = $(abc);
  var link = $(abc).find('a:contains(View My Profile)');
  //console.log (link);
  var userID = $(link).attr('href');
  var userId = $(userID);
  console.log(userId);
  console.log(userID);
});

console.log(userIdD);
console.log(userId);

I can`t start using variables "userIdD" & "userId" outside function "abc". Inside it, it works greatly. Can someone help me to use them outside it? where I'm wrong?

Declare your variables outside the function:

var userID, userId;
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
    var abc = $(abc)
    var link = $(abc).find('a:contains(View My Profile)')
    //console.log (link)
    userID = $(link).attr('href');
    userId = $(userID)
    console.log(userId)
    console.log(userID)
})
console.log(userIdD)
console.log(userId)

The problem is that userIdD is set asynchronously . The stuff that happens inside the function call happens after the stuff outside the function call.

Here's a simplified example which you can run:

 $.get('http://jsonplaceholder.typicode.com', function(){ alert('Stuff inside function happening'); }); alert('Stuff outside function happening'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Now, if we look at your code, we'll see that you're trying to console.log variables that are set inside the function call.

To go around the asynchronicity, you can make use of promises. Let's have a look at how that works...

 var valuesPromise = $.get('http://jsonplaceholder.typicode.com').then(function(serverResponse){ return { objectId: 123 }; // return stuff you want to use later }); // later in your code, you can make use of the returned value... valuesPromise.then(function(returnedValue){ alert(returnedValue.objectId); // alerts '123' }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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