我编写了一个简单的通用ajax函数,可以在我的脚本中由多个函数调用.我不知道如何将返回给ajax函数的数据返回给调用者.
// some function that needs ajax data
function myFunction(invoice) {
// pass the invoice data to the ajax function
var result = doAjaxRequest(invoice, 'invoice');
console.dir(result); // this shows `undefined`
}
// build generic ajax request object
function doAjaxRequest(data, task) {
var myurl = 'http://someurl';
$.ajax({
url: myurl + '?task=' + task,
data: data,
type: 'POST',
success: function(data) {
console.dir(data); // this shows good data as expected
return data; // this never gets back to the calling function
}
});
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将ajax数据返回给调用函数?
Bri*_*ham 13
$.ajax是异步的,所以为了获取数据,你需要将回调传递给你的doAjaxRequest函数.我已经添加了一个回调参数,doAjaxRequest而不是使用doAjaxRequest处理响应的代码的结果在回调函数中.
// some function that needs ajax data
function myFunction(invoice) {
// pass the invoice data to the ajax function
doAjaxRequest(invoice, 'invoice', function (result) {
console.dir(result);
});
}
// build generic ajax request object
function doAjaxRequest(data, task, callback) {
var myurl = 'http://someurl';
$.ajax({
url: myurl + '?task=' + task,
data: data,
type: 'POST',
success: function(data) {
console.dir(data); // this shows good data as expected
callback(data);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9289 次 |
| 最近记录: |