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

前端 未结 5 2124
爱一瞬间的悲伤
爱一瞬间的悲伤 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:16

    Instead of implementing blocking to simulate a synchronous call like someone else previously posted, just make the AJAX call itself synchronous and update your success wrapper:

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

    Edit: Although useful, this is sorta against the grain of "normal" AJAX use. I would suggest changing your approach instead.

提交回复
热议问题