jQuery:ajax请求返回值"undefined"内部相同的功能 [英] JQuery: ajax request return value "undefined" inside same function

查看:171
本文介绍了jQuery:ajax请求返回值"undefined"内部相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

function CallAPI(paramString) {
    var returnVal;
    var jqxhr = $.get(
        "http://url/../"
    )
    .success(function (data) { returnVal = data; })
    .error(function (xhr, ajaxOptions, thrownError) { alert("Error!\n xhr.status = [" + xhr.status + "]\n xhr.statusText: [" + xhr.statusText + "]\najaxOptions = [" + ajaxOptions + "]"); })
    .complete(function () { alert("Request complete."); });

    alert("returnVal: [" + returnVal+ "]");
}

最后一个警报中的"returnVal"返回为"undefined",但是当我使用Firebug调试时,我看到请求响应为"true"或"false".该值以纯字符串的形式从请求发送回,而不是特定格式(JSON,HTML,..)

The "returnVal" in the last alert is returned as "undefined", but when i debug with Firebug, I see the request response is either "true" or "false". The value is send back from the request as pure string, not specific format (JSON, HTML, ..)

为什么"returnVal"不返回请求的响应值? 谢谢

Why does "returnVal" not return the request's response value? Thanks

推荐答案

由于您在ajax调用之外使用它,并且由于ajax调用是异步的,因此警报弹出的速度比获得响应的速度快.您必须在success处理程序中使用returnVal变量,以确保获得响应返回的值.

Because you use it outside the ajax call and, as ajax calls are asynchronous, the alert pops up faster than you get the response. You have to use the returnVal variable inside the success handler, to be sure that you get the value returned by the response.

这篇关于jQuery:ajax请求返回值"undefined"内部相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆