Twitter bootstrap remote modal muestra el mismo contenido cada vez


Estoy usando Twitter bootstrap, he especificado un modal

<div class="modal hide" id="modal-item">

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">x</button>
        <h3>Update Item</h3>
    </div>

    <form action="http://www.website.com/update" method="POST" class="form-horizontal">

    <div class="modal-body">
        Loading content...
    </div>

    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
        <button class="btn btn-primary" type="submit">Update Item</button>
    </div>

    </form>

</div>

Y los enlaces

<a href="http://www.website.com/item/1" data-target="#modal-item" data-toggle="modal">Edit 1</a>
<a href="http://www.website.com/item/2" data-target="#modal-item" data-toggle="modal">Edit 2</a>
<a href="http://www.website.com/item/3" data-target="#modal-item" data-toggle="modal">Edit 2</a>

Cuando hago clic en cualquiera de estos enlaces por primera vez, veo el contenido correcto, pero cuando hago clic en otros enlaces muestra el mismo contenido cargado por primera vez, no actualiza el contenido.

Quiero que se actualice cada vez que se haga clic.

P.d.: Puedo hacer que funcione fácilmente a través de la función jQuery personalizada, pero quiero saber si es posible con nativos Función remota modal Bootstrap, ya que debería ser lo suficientemente fácil y supongo que solo estoy complicando las cosas.

Author: Cœur, 2012-09-05

22 answers

El problema es doble.

Primero , una vez que se crea una instancia de un objeto Modal, se adjunta persistentemente al elemento especificado por data-target y las llamadas posteriores para mostrar que modal solo llamará a toggle() sobre él, pero no actualizará los valores en el options. Por lo tanto, aunque los atributos href son diferentes en sus diferentes enlaces, cuando el modal está conmutado, el valor de remote no se actualiza. Para la mayoría de las opciones, uno puede evitar esto editando directamente el objeto. Por ejemplo:

$('#myModal').data('bs.modal').options.remote = "http://website.com/item/7";

Sin embargo, eso no funcionará en este caso, porque...

Segundo, el complemento Modal está diseñado para cargar el recurso remoto en el constructor del objeto Modal, lo que desafortunadamente significa que incluso si se realiza un cambio en el options.remote, nunca será recargado .

Un remedio simple es destruir el objeto Modal antes de los cambios posteriores. Una opción es simplemente destruirlo después de que termine escondiendo:

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

Nota: Ajuste los selectores según sea necesario. Este es el más general.

Émbolo

O podría intentar idear un esquema más complicado para hacer algo como comprobar si el enlace que inicia el modal es diferente del anterior. Si lo es, destruir; si no lo es, entonces no hay necesidad de recargar.

 440
Author: merv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-21 04:08:38

Para bootstrap 3 debes usar:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});
 170
Author: Camilo Nova,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-08 19:04:57

Para Bootstrap 3.1, querrá eliminar los datos y vaciar el modal-content en lugar de todo el diálogo (3.0) para evitar el parpadeo mientras espera que se cargue el contenido remoto.

$(document).on("hidden.bs.modal", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

Si está utilizando modales no remotos, el código anterior, por supuesto, eliminará su contenido una vez cerrado (malo). Es posible que necesite agregar algo a esos modales (como una clase .local-modal) para que no se vean afectados. Luego modifique el código anterior a:

$(document).on("hidden.bs.modal", ".modal:not(.local-modal)", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});
 49
Author: slopapa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-13 07:16:47

Gracias merv. Empecé a juguetear con Boostrap.js pero su respuesta es una solución rápida y limpia. Esto es lo que terminé usando en mi código.

$('#modal-item').on('hidden', function() {
    $(this).removeData('modal');
});
 30
Author: Bienvenido David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-23 15:14:50

La respuesta aceptada no funcionó para mí, así que fui con JavaScript para hacerlo.

<a href="/foo" class="modal-link">
<a href="/bar" class="modal-link">

<script>
$(function() {
    $(".modal-link").click(function(event) {
        event.preventDefault()
        $('#myModal').removeData("modal")
        $('#myModal').modal({remote: $(this).attr("href")})
    })
})
 21
Author: James Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-21 15:28:08

Esto funciona con Bootstrap 3 FYI

$('#myModal').on('hidden.bs.modal', function () {
  $(this).removeData('bs.modal');
});
 14
Author: Dave Sag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-09 05:24:58

Mi proyecto está construido en Yii y usa el plugin Bootstrap-Yii, así que esta respuesta solo es relevante si estás usando Yii.

La corrección anterior funcionó, pero solo después de la primera vez que se mostró el modal. La primera vez que salió vacío. Creo que eso es porque después de mi iniciación del código Yii llama a la función hide del modal limpiando así mis variables de iniciación.

Encontré que poner la llamada removeData inmediatamente antes del código que lanzó el modal hizo el truco. Así que mi código está estructurado así...

$ ("#myModal").removeData ('modal');
$ ('#myModal').modal ({remote : 'path_to_remote'});
 7
Author: Sean Toru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-10 10:12:19

En Bootstrap 3.2.0 el evento " on " tiene que estar en el documento y tienes que vaciar el modal :

$(document).on("hidden.bs.modal", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

En Bootstrap 3.1.0 el evento" on " puede estar en el cuerpo:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});
 5
Author: Romain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-13 07:15:37

¿Por qué no hacerlo más general con BS 3? Simplemente use "[algo]modal " como el ID del DIV modal.

$("div[id$='modal']").on('hidden.bs.modal',
    function () {
        $(this).removeData('bs.modal');
    }
);
 3
Author: user2763645,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-10 05:27:55

La única opción que funciona para mí es:

$('body').on('hidden.bs.modal', '#modalBox', function () {
    $(this).remove();
});

Uso Bootstrap 3 y tengo una función llamada popup('popup content') que añade el cuadro modal html.

 2
Author: Orkun Tuzel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-06 12:41:00

Añadiendo un $(this).html ( " ); para borrar los datos visibles también, y funciona bastante bien

 1
Author: webstr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-12 22:33:52

Si se proporciona una URL remota, el contenido se cargará una vez a través del método load de jQuery y se inyectará en el .modal-div contenido. Si está utilizando data-api, puede utilizar alternativamente el atributo href para especificar el origen remoto. Un ejemplo de esto se muestra a continuación

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
 1
Author: Ciprian Mihalache,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-24 07:35:59

He agregado algo como esto, porque el contenido anterior se muestra hasta que aparece el nuevo, con.html(") dentro del .modal-content borrará el HTML dentro, espero que ayude

$('#myModal').on('hidden.bs.modal', function () {
   $('#myModal').removeData('bs.modal');
   $('#myModal').find('.modal-content').html('');
});
 1
Author: Mau GM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-23 18:30:05

Escribí un simple fragmento manejando la actualización del modal. Básicamente almacena el enlace pulsado en los datos del modal y comprueba si es el mismo enlace en el que se ha pulsado, eliminando o no los datos modales.

var handleModal = function()
{
    $('.triggeringLink').click(function(event) {
        var $logsModal = $('#logsModal');
        var $triggeringLink = $logsModal.data('triggeringLink');

        event.preventDefault();

        if ($logsModal.data('modal') != undefined
            && $triggeringLink != undefined
            && !$triggeringLink.is($(this))
        ) {
            $logsModal.removeData('modal');
        }

        $logsModal.data('triggeringLink', $(this));

        $logsModal.modal({ remote: $(this).attr('href') });
        $logsModal.modal('show');
    });
};
 0
Author: DevAntoine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-01 12:44:14

Para Bootstrap 3, en modal.js I changed:

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open'); })

A

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { 
    $(this).removeData('bs.modal').empty()
    $(document.body).removeClass('modal-open')
  })

(espacio adicional añadido para mayor claridad)

Esto evita cualquier flash no deseado de contenido modal antiguo llamando a empty() en el contenedor modal, así como eliminando los datos.

 0
Author: Stanton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-10 20:49:38
        $('#myModal').on('hidden.bs.modal', function () {
            $(this).removeData('modal');
        });

Este funciona para mí.

 0
Author: Shawn Ang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-18 10:12:42

Este otro enfoque funciona bien para mí:

$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});
 0
Author: Rhys Stephens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 23:36:41
$('body').on('hidden.bs.modal', '.modal', function () {
       $("#mention Id here what you showed inside modal body").empty()
});

Qué elemento html desea vaciar como(div,span whatever).

 0
Author: Atul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-24 07:33:56

Este funciona para mí:

Modal

<div class="modal fade" id="searchKaryawan" tabindex="-1" role="dialog" aria-labelledby="SearchKaryawanLabel" aria-hidden="true"> <div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="SearchKaryawanLabel">Cari Karyawan</h4>
  </div>
  <div class="modal-body">
    <input type="hidden" name="location">
    <input name="cariNama" type="text" class="form-control" onkeyup="if (this.value.length > 3) cariNikNama();" />
    <div class="links-area" id="links-area"></div>
  </div>
  <div class="modal-footer">
  </div>
</div> </div></div>

Script

<script type="text/javascript">$('body').on('hidden.bs.modal', '.modal', function () {  $(".links-area").empty() }); </script>

Enlaces-área es el área donde pongo los datos y la necesidad de borrar

 0
Author: dewaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-26 09:50:43

Versión expandida de respuesta aceptada por @merv. También comprueba si el modo oculto se carga desde la fuente remota y borra el contenido antiguo para evitar que parpadee.

$(document).on('hidden.bs.modal', '.modal', function () {
  var modalData = $(this).data('bs.modal');

  // Destroy modal if has remote source – don't want to destroy modals with static content.
  if (modalData && modalData.options.remote) {
    // Destroy component. Next time new component is created and loads fresh content
    $(this).removeData('bs.modal');
    // Also clear loaded content, otherwise it would flash before new one is loaded.
    $(this).find(".modal-content").empty();
  }
});

Https://gist.github.com/WojtekKruszewski/ae86d7fb59879715ae1e6dd623f743c5

 0
Author: Wojtek Kruszewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 14:04:25

Probado en Bootstrap versión 3.3.2

  $('#myModal').on('hide.bs.modal', function() {
    $(this).removeData();
  });
 -1
Author: Abudayah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-16 09:24:44

Buena suerte con este:

$('#myModal').on('hidden.bs.modal', function () {
    location.reload();
});
 -4
Author: Mappy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-18 08:42:30