gpt4 book ai didi

javascript - jQuery MVC - 基本 jQuery if else 语句哪个不能工作?

转载 作者:行者123 更新时间:2023-12-02 20:04:30 26 4
gpt4 key购买 nike

我有一个 if-else 脚本:

     $('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');

if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});

调用isFav脚本函数:

    function isFav(fid) {

$.ajax({

url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}

这又调用我的 Controller 操作:

    public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}

一切似乎都正常,我从 firebug 中得到了 true,但是我从 else 语句中得到了警报消息。 if 语句永远不会被输入。我不明白这里出了什么问题。任何想法??请帮忙..

最佳答案

isFav 中的 ajax 请求是异步的,isFav 方法将在完成之前返回。

这可能是我解决这个问题的方法:

function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}


$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');

isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});

您想要确保 if block 中的代码在 ajax 请求完成后运行。在此代码片段中,这是通过执行 ajax success 函数时调用的回调方法解决的。

关于javascript - jQuery MVC - 基本 jQuery if else 语句哪个不能工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618912/

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