[英]Javascript Functions True or False
您好我有这个功能:
function makeTweet(params) {
var tweetID = params.tweetID;
var tweetDate = params.tweetUrl;
var tweetText = params.tweetText;
var tweetUrl = params.tweetUrl;
var authorName = params.tweetDate;
var authorNickname = params.authorNickname;
var authorAvatar = params.authorAvatar;
if ( haveOauth() == true ) {
alert("We have the account, make the reply");
}else{
alert("We do not have it");
}
}
它应该获取以下函数的结果,并了解它是否返回true或false并根据该结果执行某些操作。
我该怎么做? 无论我现在做什么,都会返回相同的结果。 这里不对劲。 谢谢
function haveOauth() {
var user_id = "1";
var data = $.ajax({
type: "POST",
url: "uspolitics_pulse/functions.php",
data: { type: 'checkOauth', user_id: user_id },
async: false,
success : function(data) {
if(data) {
return false;
}
}
});
}
async: false
永远不建议使用async: false
,但是您可以尝试替换
if(data) {
return false;
}
与
var result = false;
var data = $.ajax({
// ...
success : function(data) {
result = data;
}
});
return result;
但是为什么不让haveOath
自己回调
function haveOauth(callback) {
var user_id = "1";
var data = $.ajax({
type: "POST",
url: "uspolitics_pulse/functions.php",
data: { type: 'checkOauth', user_id: user_id },
success : function(data) {
callback(data);
}
});
}
接着
function makeTweet(params) {
var tweetID = params.tweetID;
var tweetDate = params.tweetUrl;
var tweetText = params.tweetText;
var tweetUrl = params.tweetUrl;
var authorName = params.tweetDate;
var authorNickname = params.authorNickname;
var authorAvatar = params.authorAvatar;
haveOauth(function(data) {
if (data) {
alert("We have the account, make the reply");
}else{
alert("We do not have it");
}
});
}
尝试这个:
function haveOauth() {
var result = true;
var user_id = "1";
var data = $.ajax({
type: "POST",
url: "uspolitics_pulse/functions.php",
data: { type: 'checkOauth', user_id: user_id },
async: false,
success : function(data) {
if(data) {
result = false;
}
}
});
return result;
}
与迈克尔·斯旺(Michael Swan)的答案类似-我认为您永远无法达到返回真假的境地。
function haveOauth() {
var user_id = "1";
var data = $.ajax({
type: "POST",
url: "uspolitics_pulse/functions.php",
data: { type: 'checkOauth', user_id: user_id },
async: false,
success : function(data) {
if(data) {
return false;
}
}
});
return true;
}
功能haveOauth
包括不建议是同步的,如@AdamRackis指出AJAX调用。 (除此之外,您的return
传递给回调函数内$.ajax
不会做你想要什么,你错过了一个return true
地方-看到@MichaelSwan的溶液)
您可以使用一个回调使您的代码异步,该回调通过haveOauth
中的检查结果:
function haveOauth(callback) {
var user_id = "1";
$.ajax({
type: "POST",
url: "uspolitics_pulse/functions.php",
data: { type: 'checkOauth', user_id: user_id },
success : function(data) {
if (data) { // or whatever check needs to be made
callback(true); // signal that authenticated
} else
callback(false); // signal that not authenticated
}
});
}
然后在makeTweet
使用如下功能:
haveOauth(function(isAuthenticated) {
if (isAuthenticated)
alert("We have the account, make the reply");
else
alert("We do not have it");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.