Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中,如何将数据返回给原始调用方函数?_Javascript_Jquery_Ajax_Callback_Return - Fatal编程技术网

在Javascript中,如何将数据返回给原始调用方函数?

在Javascript中,如何将数据返回给原始调用方函数?,javascript,jquery,ajax,callback,return,Javascript,Jquery,Ajax,Callback,Return,将数据返回到希望返回的函数时遇到问题。代码如下: function ioServer(request_data, callback) { $.ajax({ cache: false, data: "request=" + request_data, dataType: "json", error: function(XMLHttpRequest, textStatus, errorThrown){}, suc

将数据返回到希望返回的函数时遇到问题。代码如下:

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;   
    }   
}
我通过在另一个函数中调用processRequest函数来调用这段代码。发送请求和检索响应都可以正常工作。但是,我需要从响应返回一个值'id'给processRequest函数,这样它就可以将该值返回给它的调用者。就我所知,processResponse中的返回返回到$.ajax,但我需要它进一步返回到processRequest

顺便说一句,processResponse中的if语句引用了服务器端PHP脚本设置的一个值,用于指示是否允许该请求(例如,如果用户未登录,则fromServer.response将为0)。它与$.ajax对象的成功/错误例程没有任何关系

非常感谢你的帮助

@谢谢你的回复,但是你能再澄清一点吗?需要“id”的函数具有以下代码:

$(#tabs).tabs('add', '#tab-' + id, 'New tab');

你是说我应该尝试在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
    } 
}

不要像其他人之前发布的那样实现阻塞来模拟同步调用,只需使AJAX调用本身同步并更新成功包装器:

function ioServer(request_data, callback) {
    var response = null;
    $.ajax({
        cache: false,
        data: "request=" + request_data,
        dataType: "json",
        error: function(XMLHttpRequest, textStatus, errorThrown){},
        success: function(response_data, textStatus) {
                response = callback(response_data);
        },
        timeout: 5000,
        type: "POST",
        url: "/portal/index.php/async",
        async: false
    });

    return response;
}

编辑:虽然有用,但这与“正常”AJAX使用的粒度有点不符。我建议改变你的方法。

因为托尼没有提供任何评论,让我补充一下他建议的细节

正如您所了解的,processRequest函数在进行$.ajax调用后立即完成,因为$.ajax方法是异步的。那么,您将如何通知processRequest的调用方任务已完成

很简单,您要求processRequest的调用方提供一个“回调函数”。processRequest将在收到ajax输出时调用此函数。在tony的代码中,这是processRequest函数的最后一个参数

因此,您的呼叫代码现在看起来像

function tabMethod() {
    processRequest('command', 'item', 'properties',
        function (id) {
            if (id == null) {
                alert('There is a problem!');
                return;
            }
            $('#tabs').tabs('add', '#tab-' + id, 'New tab');
        });
};

太棒了!谢谢你们的帮助,现在很有魅力。我学会了更好地使用回调。以下是完整的工作代码:

createTab('#tabs'); // I'm using JQuery UI to handle tabs    

function createTab(parent_element){
            var name = {};
            name.name = "New tab";
            var position = {};
            position.position = $(parent_element).tabs('length') + 1;
            var properties = new Array();
            properties[0] = name;
            properties[1] = position;
            processRequest(1, 1, properties, 
                      function(id)
                      {
                         if(id == null) 
                         {
                              alert('There is a problem!');
                              return;
                         }
                         $('#tabs').tabs('add', '#tab-' + id, 'New tab');
                      });
        }

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
    } 
}
它会在页面列表的末尾添加一个新选项卡。正如我所希望的,它现在也通过PHP和MySQL存储在服务器端


再次感谢

您不想进行同步调用,因为如果ajax请求不能很快完成,它可能会冻结浏览器。@solutionyogi Hah,ya,当您发表评论时,我正在对此进行编辑。然而,我(不情愿地)在过去这样做,没有浏览器冻结问题。据我所知,JavaScript只是等待/阻塞,不执行任何操作。为您的代码建议和调用代码的外观添加了解释。我希望你不介意。如果我想从ioServer返回对processRequest的响应,并且如果有1个以上的函数正在调用ioServer,因此我不确定请求者函数名,该怎么办?是的,感谢您对使用进行更明确的说明!