gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:30:23 25 4
gpt4 key购买 nike

我有一个函数,它将返回 AJAX 响应并将其用于另一个函数。这是我的代码:

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);

这是 getExistingId() 的代码

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();
}

当我测试代码时,我的查询或 PHP 代码没有问题,因此我不会将其包含在此处,但为什么是 usid总是返回未定义?

最佳答案

仔细看,您在 getEditistingId() 函数中缺少回调参数。请执行以下操作:

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);
});

关于JavaScript 回调函数在我的情况下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com