我有一个ajax
电话,如
$.ajax({
type: 'POST',
url: 'addVideo',
data: {
video_title: title,
playlist_name: playlist,
url: id
// csrfmiddlewaretoken: '{{ csrf_token }}',
},
done: bootstrap_alert.success('video saved successfully'),
fail: bootstrap_alert.error('There were some errors while saving the video. Please try in a while')
});
和
的行动// setting up alerts on action
bootstrap_alert = function() {}
bootstrap_alert.success = function(message) {
$('#feature').prepend('<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>');
}
bootstrap_alert.error = function(message) {
$('#feature').prepend('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>');
}
当前端进行ajax呼叫时,我同时看到两个通知
video saved successfully
There were some errors while saving the video. Please try in a while
我是不是正确地进行了ajax调用?
更新
将done
更改为success
会导致相同的行为
// send the data to the server using .ajax() or .post()
$.ajax({
type: 'POST',
url: 'addVideo',
data: {
video_title: title,
playlist_name: playlist,
url: id
// csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: bootstrap_alert.success('video saved successfully'),
fail: bootstrap_alert.error('There were some errors while saving the video. Please try in a while')
});
服务器响应为HTTP/1.0" 200 3200
,我认为fail
不应该被调用
答案 0 :(得分:17)
这些值应该是函数,回调。但是,你正在做的是马上打电话给他们。用匿名函数包装你的回调。
$.ajax({
type: 'POST',
url: 'addVideo',
data: { video_title: title, playlist_name: playlist, url: id }
}).done(function(){
bootstrap_alert.success('video saved successfully');
}).fail(function(){
bootstrap_alert.error('There were some errors while saving the video. Please try in a while');
});
答案 1 :(得分:7)
done
。这应该发生。您应该在success
属性中处理您的成功代码。
答案 2 :(得分:2)
您需要将其包装在匿名函数中(正如其他人所说)。但是,我没有看到有人提到为什么(我认为值得一提)。
您需要执行此操作的原因是因为javascript将冒号右侧的评估分配给左侧。为了评估右侧,它需要首先运行您的功能。但是如果在右侧有一个匿名函数,它将函数本身定义为左侧引用的值(在javascript中,变量的值可以是函数)并将函数指定为左侧side(现在是函数的引用)。因此,它会延迟评估(运行函数),直到你的ajax调用完成。
答案 3 :(得分:1)
这样改变
// send the data to the server using .ajax() or .post()
$.ajax({
type: 'POST',
url: 'addVideo',
data: {
video_title: title,
playlist_name: playlist,
url: id
// csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
bootstrap_alert.success('video saved successfully');
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
// log the error to the console
console.log("The following error occured: "+ textStatus, errorThrown);
bootstrap_alert.error('There were some errors while saving the video. Please try in a while');
},
});
答案 4 :(得分:0)
尝试将done
替换为success
,将fail
替换为error
?你在回调挂钩时使用它们作为选项。