Ajax成功函数不能返回值

时间:2014-09-29 06:01:56

标签: php jquery ajax

我正在使用jQuery ajax函数来获取数据库值代码和子代码。每当我得到代码和子代码时,我必须将名称存储在与代码和子代码相对应的另一个表中。  我正在使用的第一个功能是

function loadSecretaries()
{
    var items = "";
    $.getJSON("Tac_members_GetTacSecretaries.php", function(data) {

        $.each(data, function(index, item) {
            var name = getSecretariesName(item.ECODE, item.ECODE_S);
            items += "<option value='" + item.ECODE + "'>" + item.ECODE_S + </option>";    
        });
        $("#select_reviewer_secretary").html(items);
    });

}

第二个功能是

function getSecretariesName(code, subcode)
{

    var items = "";
    $.ajax({
        async: false,
        url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
        dataType: 'json',
        type: 'POST',
        data: {"code": code, "subcode": subcode},
        success: function(response) {
            alert(response.ename) ;
           var name =response.ename;
        //here i want to return ename to first function
        },
        error: function(x, e) {
            if (x.status === 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status === 404) {
                alert('Requested URL not found.');
            } else if (x.status === 500) {
                alert('Internel Server Error - Please try after relogin to the application');
            } else if (e === 'parsererror') {
                alert('Parsing JSON Request failed.');
            } else if (e === 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }

    });
return name;
}

当我发出警告时,我会收到undefined姓名&#39;在第一个功能。怎么解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个

   function getSecretariesName(code, subcode)
{

    var items = "";
    var name = "";
    $.ajax({
        async: false,
        url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
        dataType: 'json',
        type: 'POST',
        data: {"code": code, "subcode": subcode},
        success: function(response) {
            alert(response.ename) ;
           name = response.ename;
        //here i want to return ename to first function
        },
        error: function(x, e) {
            if (x.status === 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status === 404) {
                alert('Requested URL not found.');
            } else if (x.status === 500) {
                alert('Internel Server Error - Please try after relogin to the application');
            } else if (e === 'parsererror') {
                alert('Parsing JSON Request failed.');
            } else if (e === 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }

    });
return name;
}