功能未将值返回给其他功能 [英] Function not returning value to other function
问题描述
试图编写一个从文本文件中读取数据的函数.该功能工作正常,但我想在其他功能中读取其数据.有人可以帮我讲一下如何将y的值返回给read()函数
Tried to write a function which reads data from a text file. The function is working fine but I want to read its data in other function. Could some one help me telling how to return the value of y to read() function
<!DOCTYPE html>
<html>
<head>
<script charset="utf-8" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript">
function read() {
$.get("version.txt?_ts=" + new Date().getTime(), function (data) {
var y1 = parseInt(data[0]);
var y2 = parseInt(data[1]);
var y = (y1 * 10) + y2;
return y;
});
}
function drr() {
var d = read();
document.write(d);
}
</script>
<body onload=read()>not working</body>
</html>
推荐答案
在您的代码中,您正在使用AJAX槽式JQuery:
In your code you are using AJAX trough JQuery:
$.get(url, callback)
$get
方法命中url
并将结果传递给回调方法,但不返回.由于AJAX是异步的,因此callback
不会立即被调用,而是发生以下情况:
The $get
method hits the url
and passes the result to the callback method, it does not return it. The callback
does not get invoked immediately, due to AJAX being asynchronous, instead something like this happens:
-
$.get
被称为 -
read
方法继续(在您的情况下退出,因为没有其他代码) -
$.get
收到来自服务器的响应 - 如果服务器成功获取数据,则会调用
callback
函数
$.get
is called- the
read
method continues (exits in your case, as there is no other code) - the
$.get
receives a response from the server - the
callback
function gets called, if the server succeeded with getting the data
在上述顺序中,第二步可以替换为第二步之后的任何步骤.尽管如此,此顺序仍显示 read
方法退出时和数据处理发生时之间没有任何关联.因此,如果您需要对结果做一些事情(在页面上显示),则应该在callback
方法内部进行.
In the above sequence, the second step may be swapped with any of the steps after it. Still, this sequence is to show that there is no relationship between when the read
method exits and when the processing of the data occurs. So, if you need to do something with the result (show it on the page) then you should do this inside the callback
method.
以下是您的代码经过修改的示例:
Here is an edited example with your code:
function read() {
$.get("version.txt?_ts=" + new Date().getTime(), function(data) {
var y1 = parseInt(data[0]);
var y2 = parseInt(data[1]);
var y = (y1*10)+y2;
document.write(y);
});
}
除了AJAX的异步特性外,您的代码还有另一个问题.在您的read
方法中,您希望返回一个值,但实际上它不返回任何值.这导致drr
函数无效.
In addition to the asynchronous nature of AJAX, there is another problem with your code. In your read
method, you expect to return a value, but actually it does not return anything. This renders the drr
function to be invalid.
这篇关于功能未将值返回给其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!