代码之家  ›  专栏  ›  技术社区  ›  Alex Pliutau

jQuery Ajax成功变量

  •  1
  • Alex Pliutau  · 技术社区  · 14 年前

    我有下一个功能。我的PHP脚本返回一个带有元素的数组 error 值为'ERR':

    var updatePaymentType = function(plan_pt_id, pt_id){
        var error = null;
        var data = new Object()
        data["function"]             = "update";
        data["payment_type_id"]      = pt_id;
        data["plan_payment_type_id"] = plan_pt_id;
        data["data"]            = $("#saveform").serializeArray();
        $.ajax({
            type: "POST",
            url: "<?=ROOT_PATH?>/commission/plan/edit/id/<?=$this->editId?>",
            data: data,
            dataType: "json",
            success : function (data)
            {
                error = data['error'];
                alert(error); // All works. Output ERR
            }
        });
        alert(error); // Not work. Output null
        return error;
    };
    

    我的函数应该返回一个错误。但它又回来了 null . 非常感谢你。

    1 回复  |  直到 14 年前
        1
  •  6
  •   Nick Craver    14 年前

    AJAX请求是异步的,这意味着在 之后 success 处理程序运行 后来 ,当服务器以数据响应时)。

    返回 必须使其与同步的错误类型 async: false 这样地:

    $.ajax({
        async: false,
        type: "POST",
        ...
    

    但这会锁定浏览器,最好调用 成功 回拨,如下所示:

        success : function (data)
        {
            var error = data['error'];
            functionThatTakesError(error);
        }
    
    推荐文章