函数返回 Ajax 响应 - 值未定义?jQuery Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10795516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:46:25  来源:igfitidea点击:

Function returns Ajax response - Value is undefined? jQuery Ajax

jqueryajaxjson

提问by TaylorMac

When I alert the returned value from the jsonServerResponse function, its value is undefined - despite JSON being returned from the process.php page.

当我提醒 jsonServerResponse 函数返回的值时,它的值是未定义的——尽管从 process.php 页面返回了 JSON。

function jsonServerResponse(operation, JSOoptionalData) {
        JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
        var jqxhr = $.ajax({
            type: "POST",
            url: "process.php",
            data: "apicommand=" + JSOoptionalData,
            success: function (json) {
                return jQuery.parseJSON(json);
            }
        });
}

alert("Response as JS Object: "+jsonServerResponse("operation"));

I know that the problem is that the alert function made before the asynchronous request is complete, but I am unsure how to fix this problem. Any advice is really appreciated :)

我知道问题是在异步请求完成之前进行了警报功能,但我不确定如何解决这个问题。任何建议都非常感谢:)

回答by Rory McCrossan

This is because the AJAX request is asynchronous, so the returnis hit before the call completes, so the function always returns null.

这是因为 AJAX 请求是异步的,所以return在调用完成之前就命中了,所以函数总是返回 null。

You need to call the code which relies on the AJAX call, from within the successcall back itself. Try this:

您需要从success回调本身内部调用依赖于 AJAX 调用的代码。尝试这个:

function jsonServerResponse(operation, JSOoptionalData) {
    JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
    var jqxhr = $.ajax({
        type: "POST",
        url: "process.php",
        data: "apicommand=" + JSOoptionalData,
        success: function (json) {
            alert("Response as JS Object: " + json);

            // to see more information about the object returned, use console.log:
            console.log(json);
        }
    });
}

jsonServerResponse("operation")

回答by TaylorMac

Ok, I figured it out from a different post. The result can either be handled within the success callback, or you can add an argument that is itself a callback function and apply the result of the ajax request to the callback.

好的,我从另一个帖子中弄清楚了。结果既可以在成功回调中处理,也可以添加一个本身就是回调函数的参数,并将 ajax 请求的结果应用于回调。

function jsonServerResponse(operation, callback, JSOoptionalData) {
        JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
        jqxhr = $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "process.php",
            data: "apicommand=" + operation + "&optionaldata" + JSON.stringify(JSOoptionalData),
            dataType: "json",
            success: function (json) {
                if(typeof callback === 'function') callback.apply(this, [json]);
            }
        });
}


jsonServerResponse("get_something_from_server", function(returnedJSO){
     console.log(returnedJSO.Result.Some_data);
}, "optional_data");

And gdoron, the line you have asked about makes the third argument optional. I hear it's good practice, if you are going to pass some data onto the server (but you dont know how many variables) to add an optional argument and just pass a js object, convert this to a JSON string, and decode it server-side.

和 gdoron,你问的那一行使第三个参数是可选的。我听说这是一个很好的做法,如果您要将一些数据传递到服务器(但您不知道有多少变量)以添加一个可选参数并只传递一个 js 对象,将其转换为 JSON 字符串,然后将其解码服务器-边。

Peace! :)

和平!:)

回答by gdoron is supporting Monica

You nailed the problem, ajax is an async operation, you can use the returned data only in the success callback:

您解决了问题,ajax 是一个异步操作,您只能在成功回调中使用返回的数据:

function jsonServerResponse(operation, JSOoptionalData) {
    // What that line suppose to do???
        JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
        var jqxhr = $.ajax({
            type: "POST",
            url: "process.php",
            data: "apicommand=" + JSOoptionalData,
            dataType: "json", // Change the dataType to json.
            success: function (json) {
                console.log("Response as JS Object:") 
                console.log(json);
            }
        });
}