jQuery post inside another javascript function
I have some code like:
function duplicatecheck(value, colname) {
var invoiceLineId = $('tr[editable="1"]').attr('id');
var invoiceLine = {
InvoiceLineId: invoiceLineId,
InvoiceId: invoiceId,
ActivityId: value
};
$.post('/Invoice/InvoiceLineExistsForThisActivity/', invoiceLine, function (data) {
if(data == true) {
return[ false, "An invoice line already exists with this activity"]
}
else {
return[ true, ""];
}
});
}
The problem is that duplicatecheck
开发者_如何转开发is supposed to return a value. The value is inside the post
callback function. So duplicatecheck
runs and doesn't return anything because post
is asynchronous and duplicatecheck
finishes before the callback has even run.
Is there a way to make duplicatecheck
wait until the callback has finished and return what the callback returns.
Am I going about this completely the wrong way and should be doing something else?
- I think you go the wrong way, JS is event driven, mostly
- The $.POST has a sync/async flag, check here
If you use jQuery.ajax you have the power to set async to false. That being said, preferably your web application should be structured in such a way that asynchronism is possible.
You should look into callbacks. If you run a function you know might take a while, provide it with a function that it will call when it's done. Useful links:
Understanding callback functions in Javascript
Getting a better understanding of callback functions in JavaScript
精彩评论