在我的情况下,JavaScript回调函数不起作用

时间:2015-07-21 01:52:30

标签: javascript ajax callback return return-value

我有一个函数将返回一个AJAX响应并在另一个函数上使用它。这是我的代码:

DECLARE @type NUMBER;
SELECT TYPE INTO @type FROM DUAL; -- Make sure it always returns one row

IF @type = 1 THEN
    SELECT A.name 
    FROM BIZZXE_V2_SCH.SUPPLIERS A
    WHERE A.SUPPLIER_ID = 30;
ELSE
    SELECT A.name 
    FROM BIZZXE_V2_SCH.STOCK_SUPPLIER A
    WHERE A.SUPPLIER_ID = 31
END IF;

这是getExistingId()

的代码
function updateLoanApproval(answer){
    var password = document.getElementById("password").value;
    var usid; 
    getExistingId(function(success){
        if (success === 0){
            var usid = "No ID Available";
        } else {
            var usid = success; //To get the returning value
        }
    });

    alert(usid);

在测试代码时,我对查询或PHP代码没有问题所以我不会在这里包含它,但为什么function getExistingId(){ var url = "../../library/functions.php?action=getId"; var uid; http.onreadystatechange = function(){ if (http.status == 200 && (http.readyState === 4)){ uid = http.responseText; if (uid == "No ID"){ callback(0); } else { callback(id); } } } http.open("GET",url,true); http.send(); } 总是返回undefined?

1 个答案:

答案 0 :(得分:1)

仔细看,你在getEdiistingId()函数中缺少回调参数。如下所示:

function getExistingId(callback){
var url =  "../../library/functions.php?action=getId";
var uid;
http.onreadystatechange = function(){
    if (http.status == 200 && (http.readyState === 4)){
        uid = http.responseText;
        if (uid == "No ID"){
            callback(0);
        } else {
            callback(id);
        }
    }
}

http.open("GET",url,true);
http.send();

}

并在回调方法中设置警报。

function updateLoanApproval(answer){
    var password = document.getElementById("password").value;
    var usid; 
    getExistingId(function(success){
        if (success === 0){
            var usid = "No ID Available";
        } else {
            var usid = success; //To get the returning value
        }
        alert(usid);
    });

需要usid的方法:

function doMyTaskThatNeedUsid(usid)
{
    // do something.
}

并调用如下方法:

function updateLoanApproval(answer){
    var password = document.getElementById("password").value;
    var usid; 
    getExistingId(function(success){
        if (success === 0){
            var usid = "No ID Available";
        } else {
            var usid = success; //To get the returning value
        }

        // Calling method that need usid.
        doMyTaskTaskThatNeedUsid(usid);
    });