This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 31 answers
如何从异步调用返回响应? 31个答案
I have this in my HTML code
我的HTML代码中有这个
<script type="text/javascript">
var URL = replace();
alert(URL);
</script>
If I put this in header, alert shows “http://example.com/result"
如果我把它放在标题中,则会显示“http://example.com/result”
function replace() {
url = 'http://example.com';
$.get(url, function(data){
var url_gen = data.responseText;
});
return “http://example.com/result";
}
But if I use return like this, it won't do anything. Why?
但如果我像这样使用返回,它将不会做任何事情。为什么?
function replace() {
url = 'http://example.com';
$.get(url, function(data){
var url_gen = data.responseText;
});
return url_gen;
}
Just to make sure, If I insert alert(url_gen) in front of return url_gen; in 2nd code, alert shows 'http://example.com' so url_gen has an actual value in it!
只是为了确保,如果我在返回url_gen之前插入alert(url_gen);在第二个代码中,警报显示'http://example.com',因此url_gen中有一个实际值!
Note: Here, assuming that url_gen is the string which is web-scraped from a web page.
注意:这里,假设url_gen是从网页上进行网页抓取的字符串。
2 个解决方案
#1
1
Make url_gen global like below:
使url_gen全局如下:
function replace() {
url = 'http://example.com';
var url_gen ='';
$.get(url, function(data){
url_gen = data.responseText;
});
return url_gen;
}
#2
1
Because 1) url_gen
only defined in $.get()
, can't be accessed outside; 2) $.get()
is async.
因为1)url_gen只在$ .get()中定义,不能在外面访问; 2)$ .get()是异步的。
Workaround: return directly from $.get()
:
解决方法:直接从$ .get()返回:
function replace() {
url = 'http://example.com';
$.get(url, function(data){
var url_gen = data.responseText;
return url_gen;
});
}
#1
1
Make url_gen global like below:
使url_gen全局如下:
function replace() {
url = 'http://example.com';
var url_gen ='';
$.get(url, function(data){
url_gen = data.responseText;
});
return url_gen;
}
#2
1
Because 1) url_gen
only defined in $.get()
, can't be accessed outside; 2) $.get()
is async.
因为1)url_gen只在$ .get()中定义,不能在外面访问; 2)$ .get()是异步的。
Workaround: return directly from $.get()
:
解决方法:直接从$ .get()返回:
function replace() {
url = 'http://example.com';
$.get(url, function(data){
var url_gen = data.responseText;
return url_gen;
});
}