简体   繁体   English

$ .get的javascript函数不会返回值

[英]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. 我正在使用jquery $ .get来解析URL,如果我不使用函数就可以正常工作,但是该函数将返回空字符串。 Clearly I'm doing something wrong, but I don't know what; 显然我做错了,但是我不知道是什么。 any help would be highly appreciated. 任何帮助将不胜感激。

The call to $.get is asynchronous. $ .get的调用是异步的。 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. $.get返回时,您需要传递一个要调用的函数。 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. 由于.get()异步操作,因此parseLink()继续执行并在AJAX调用返回之前返回空的新newlink

You'll need to trigger whatever is working with newlink from the callback, which may need you to rethink your implementation a little. 您需要从回调中触发对newlink进行任何处理,这可能需要您重新考虑一下实现。 What comes next (what should then happen to the populated newlink )? 接下来是什么(填充的newlink发生什么情况)?

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

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