jQuery MVC - 基本 jQuery if else 语句哪个不能工作?
我得到了一个 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; }
});
}
它又调用我的控制器操作:
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 语句永远不会被输入。 我不明白这里出了什么问题。有什么想法吗?请帮忙..
I got an if-else script:
$('#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?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
isFav 中的 ajax 请求是异步的,isFav 方法将在完成之前返回。
这可能就是我解决这个问题的方法:
您想要确保 if 块中的代码在 ajax 请求完成后运行。在此代码片段中,这是通过执行 ajax success 函数时调用的回调方法解决的。
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
您并没有真正从 isFav 函数中返回 true 。另外,ajax 是异步的,因此您的代码(if 语句)实际上会继续执行,直到 ajax 完成,因此在执行时 isFav 的结果是未定义的。这就是 else 被执行的原因。
你需要进行一些改造。
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.