等待AJAX,然后继续执行单独的功能 [英] Wait for AJAX before continuing through separate function
问题描述
好的...凌晨2点,这是我画线的地方.求助...在我的笔记本电脑最终没出窗户之前. :)
Alright... at 2am, this is where I draw the line. Help... before my laptop ends up going out the window. :)
我已经尝试过使用setTimer,回调和我能想到的所有其他功能(当然还有其他一些Stackoverflow提示).我已经剥离了所有内容,所以只剩下基本代码.
I've tried using setTimer, callbacks, and everything else I can think of (along with a few other Stackoverflow hints of course). I've stripped out everything so I'm leaving just the base code.
我想要做的是调用parseRow(),然后在最后保存记录之前,我需要获取关联的Category(通过AJAX);但是,它吹过去了,因此类别始终是未定义".
What I'm looking to do is call parseRow() and before it saves the record at the end, I need to grab the associated Category (via AJAX); however, it blows right past it so category is always "undefined".
function parseRow(row){
var rowArray = row.trim().split(",");
var date = rowArray[0];
var checknum = rowArray[1];
var payee = rowArray[2];
var memo = rowArray[3];
var amount = rowArray[4];
//ERROR: blows right past this one and sets the category variable BEFORE ajax returns
var category = autoSelectCategory(payee);
saveRecord(date, checkNum, payee, memo, category, payment, deposit);
}
function autoSelectCategory(payee) {
var data;
$.ajax({
async: false,
url: "autoselectcategory",
dataType: "json",
data: {
string: payee
},
success: function (returnedData) {
data = returnedData;
}
});
return data;
}
推荐答案
AJAX表示异步.这意味着在您的原始代码中,saveRecord
将在客户端收到服务器的响应之前执行(并且根据$.ajax
的实现,可能在客户端发送之前请求到服务器).
AJAX stands for asynchronous. That means that in your original code, saveRecord
will be executed before the client will receive the response from the server (and, depending on the $.ajax
implementation, it might be before the client will send the request to the server).
此外,您似乎误解了JS中函数的工作方式. var category = autoSelectCategory(payee);
将类别设置为autoSelectCategory
的返回值;但是代码中的autoSelectCategory
函数什么也不返回.
Additionally, you seem to misunderstand how functions work in JS. var category = autoSelectCategory(payee);
will set the category to the return value of autoSelectCategory
; but the autoSelectCategory
function in your code returns nothing.
另一方面,匿名函数的data
返回值只能由$.ajax
函数使用($.ajax
可能会忽略success
参数的返回值).
From the other side, the data
return value of your anonymous function could only be used by $.ajax
function (and $.ajax
likely ignores the success
parameter return value).
这是应该起作用的代码:
Here is the code that should work:
function parseRow(row){
var rowArray = row.trim().split(",");
var date = rowArray[0];
var checknum = rowArray[1];
var payee = rowArray[2];
var memo = rowArray[3];
var amount = rowArray[4];
autoSelectCategory(payee, function (category) {
saveRecord(date, checkNum, payee, memo, category, payment, deposit);
});
}
function autoSelectCategory(payee, callback) {
$.ajax({
async: false,
url: "autoselectcategory",
dataType: "json",
data: {
string: payee
},
success: callback
});
}
这篇关于等待AJAX,然后继续执行单独的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!