2 javascript ajax jquery return callback
我有一个问题,将数据返回到我希望它返回的函数.代码如下:
function ioServer(request_data, callback)
{
$.ajax({
cache: false,
data: "request=" + request_data,
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown){},
success: function(response_data, textStatus){
callback(response_data);
},
timeout: 5000,
type: "POST",
url: "/portal/index.php/async"
});
}
function processRequest(command, item, properties)
{
var request = {};
request.command = command;
request.item = item;
request.properties = properties;
var toServer = JSON.stringify(request);
var id = ioServer(toServer, processResponse);
return id;
}
function processResponse(fromServer)
{
if (fromServer.response == 1)
{
return fromServer.id;
}
}
Run Code Online (Sandbox Code Playgroud)
我通过调用另一个函数中的processRequest函数来调用这段代码.发送请求和检索响应工作正常.但是,我需要将响应中的值'id'返回给processRequest函数,因此它可以将该值返回给它的调用者.据我所知,processResponse中的返回值返回$ .ajax,但是我需要它返回到processRequest.
BTW processResponse中的if语句是指服务器端PHP脚本设置的值,用于判断是否允许该请求(例如,如果用户未登录,则fromServer.response将为0).它与$ .ajax对象的成功/错误例程没有任何关系.
非常感谢您的帮助.
@Jani:感谢你的回复,但是你能澄清一下吗?需要'id'的函数具有以下代码:
$(#tabs).tabs('add', '#tab-' + id, 'New tab');
Run Code Online (Sandbox Code Playgroud)
你是说我应该尝试在processResponse函数中执行这段代码吗?因为那不是我打算做的; 这些功能旨在成为维护状态服务器端的通用解决方案.这就是我避免将这段代码放在那里的原因.
我想也许这更接近你所寻找的......
function ioServer(request_data, callback)
{
$.ajax({
cache: false,
data: "request=" + request_data,
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown){},
success: function(response_data, textStatus){
processResponse(response_data, callback);
},
timeout: 5000,
type: "POST",
url: "/portal/index.php/async"
});
}
function processRequest(command, item, properties, callback)
{
var request = {};
request.command = command;
request.item = item;
request.properties = properties;
var toServer = JSON.stringify(request);
ioServer(toServer, callback);
}
//internal callback to handle response code
function processResponse(fromServer, callback)
{
if (fromServer.response == 1)
{
//call the callback with the id
callback(fromServer.id);
}
else
{
//You have to remember to call the callback no matter what
//or the caller won't know when it's complete
callback(null); //or some other "didn't get a valid response" value
}
}
Run Code Online (Sandbox Code Playgroud)