How does one return data to the original caller function in Javascript?

前端 未结 5 2129
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 15:42

I have a problem returning data back to the function I want it returned to. Code below:

function ioServer(request_data, callback)
{
    $.ajax({
        cach         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-18 16:05

    I think maybe this is closer to what you are looking for...

    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
        } 
    }
    

提交回复
热议问题