2011-12-20 46 views
2

我有以下功能:

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; 

} 

我使用jQuery $不用彷徨分析一个URL,如果我去做了,工作正常无功能,但该函数将返回空字符串。显然我做错了什么,但我不知道是什么;任何帮助将不胜感激。

+0

您是否要求从另一个域中的URL:

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); }); } 

然后你可以用打电话了吗? – isNaN1247 2011-12-20 21:09:38

+0

可能重复的[Javascript回调 - 如何返回结果?](http://stackoverflow.com/questions/6453295/javascript-callback-how-to-return-the-result) – hugomg 2011-12-20 21:10:05

+0

不,来自同一个域该URL将被发送到我的后端为“异步意大利面条”生成一个安全密钥 – isJustMe 2011-12-20 21:12:37

回答

3

您需要传入一个函数,以便在$.get返回时调用。喜欢的东西:

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

对$ .get的调用是异步的。请参阅控制流是这样的:

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(); 

我想你的意思做的是:

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 ... */ }); 

欢迎异步面条世界:)

+0

+1,它的确是。 – James 2011-12-20 21:19:50

+0

哦,顺便说一下......既然你使用jQuery,你可以看看http://api.jquery.com/jQuery.when/。如果你头脑发热,它会更容易(更线性)读取/写入,我认为... – mfeineis 2011-12-20 21:25:38

0

因为.get()异步运行,parseLink()进行在AJAX调用返回之前执行并返回空的newlink

您需要从回调中触发与newlink一起工作的任何内容,这可能需要您重新考虑一下您的实施。接下来会发生什么(人口稠密的newlink)?