Подтвердить что ты не робот

JQuery: ajax запускает оба обработчика - выполняется и не работает

У меня есть вызов 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?

UPDATE
изменение 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 не должен называться

4b9b3361

Ответ 1

Ожидается, что значения будут функциями, обратными вызовами. Но то, что вы делаете, вызывает их сразу. Обменивайте свои обратные вызовы анонимными функциями.

$.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');
});

Ответ 2

done всегда вызывается. Это должно произойти. Вы должны обрабатывать свой код успеха в свойстве success.

Ответ 3

Вам нужно обернуть его анонимной функцией (как отмечали другие). Но я не видел, чтобы кто-нибудь упоминал, почему (что, я думаю, стоит упомянуть).

Причина, по которой вам нужно это сделать, - это то, что javascript присваивает оценку правой стороне двоеточия в левой части. Чтобы оценить правильную сторону, нужно сначала запустить вашу функцию. Однако, если у вас есть анонимная функция с правой стороны, она сама определяет функцию как значение ссылки слева (в javascript значение переменной может быть функцией) и назначает функцию как есть слева (теперь это ссылка на функцию). Таким образом, это задерживает оценку (выполняется функция), пока ваш вызов ajax не завершится.

Ответ 4

как это работает

// 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');
            },
        });

Ответ 5

Попробуйте заменить done на success и fail на error? Вы используете их как опции, в то время как они являются обратными вызовами.