简体   繁体   中英

javascript function with $.get won't return value

I have the following function:

function parseLink(link){
 var newlink="";

 $.get(link,
   function(data){    

   startoffset = data.indexOf("location.replace") + 18;
   endoffset = data.indexOf("tiny_fold = 1;") - 8;
   newlink= data.substr(startoffset,(endoffset-startoffset));


});

return newlink;

 }

I'm using jquery $.get to parse a URL, which works fine if I do it without a function, but the function will return the empty string. Clearly I'm doing something wrong, but I don't know what; any help would be highly appreciated.

The call to $.get is asynchronous. See the control flow is like this:

parseUrl("http://www.test.com")
$.get(..., function callback() { /* this is called asynchronously */ })
return "";
... 
// sometime later the call to $.get will return, manipulate the
// newLink, but the call to parseUrl is long gone before this
callback();

I think what you meant to do is:

function parseUrl(link, whenDone) {
    $.get(link, function () {
        var newLink = "";
        // Do your stuff ...
        // then instead of return we´re calling the continuation *whenDone*
        whenDone(newLink);
    });
}

// Call it like this:
parseUrl("mylink.com", function (manipulatedLink) { /* ... what I want to do next ... */ });

Welcome to async spaghetti world :)

You'll need to pass in a function to be called when $.get returns. Something like:

function parseLink(link, callback) {
   $.get(link,
      function(data) {
         startoffset = data.indexOf("location.replace") + 18;
         endoffset = data.indexOf("tiny_fold = 1;") - 8;
         var newlink= data.substr(startoffset,(endoffset-startoffset));
         callback(newlink);
      });
 }

Then you can call it with:

parseLink('foo', function (newlink)
  {
     //Stuff that happens with return value
  }
);

Because the .get() operates asynchronously, parseLink() carries on executing and returns the empty newlink before the AJAX call has returned.

You'll need to trigger whatever is working with newlink from the callback, which may need you to rethink your implementation a little. What comes next (what should then happen to the populated newlink )?

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