我有这个功能。但是如何从我的2个txt文件函数中获取数据? 我希望在我的警报中输出Tabt值。
function getWeight(){
var fileKevin = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
var fileHeidi = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
//GET DATA FOR KEVIN
$.get(fileKevin,function(txt){
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
});
//GET DATA FOR HEIDI
$.get(fileHeidi,function(txt){
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
});
alert(Tabt) //function Kevin
alert(Tabt) //function Heidi
};//end getWeight
你可以帮帮我吗?
请忽略这一点: 添加文字 添加文字
添加文字
添加文字
答案 0 :(得分:2)
您无法从$.get
之类的异步函数返回数据,您必须使用回调。
您得到的是延期或承诺对象,您可以这样分组:
var call1 = $.get(fileKevin...
var call2 = $.get(fileHeidi...
$.when( call1, call2 ).done(function ( txtKevin, txtHeidi ) {
结帐$.when
你应该重构,因为你有重复的代码
示例:
function getWeight() {
var fileKevin = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
var fileHeidi = "https://dl.dropboxusercontent.com/s/mytextfile1.txt";
$.when(
$.get(fileKevin),
$.get(fileHeidi)
).done(function (txtKevin, txtHeidi) {
var weightKevin = parseWeight(txtKevin),
weightHeidi = parseWeight(txtHeidi);
console.log(weightKevin, weightHeidi);
// here you will call any function that has to use those values like:
// doSomething(weightKevin, weightHeidi);
});
function parseWeight(txt) {
var lines = txt.split("\n");
var total = parseInt(lines.length)
var first = parseInt(0)
var last = parseInt(total-1)
var prev = parseInt(total-2)
var NuVaegt = (splitWeight(lines[last],1))
var StartVaegt = splitWeight(lines[first],1);
var ForrigeVaegt = splitWeight(lines[prev],1)
var Tabt = decimal((NuVaegt-StartVaegt),1)
var Sidst = decimal((NuVaegt-ForrigeVaegt),1)
return Tabt;
}
};