Load JSON data into a Bootstrap modal

前端 未结 1 871
长发绾君心
长发绾君心 2020-12-30 16:51

I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person\'s picture, the modal pops up.

  • 1条回答
    •  天涯浪人
      2020-12-30 16:57

      Method 1: using Ajax

      Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.

      HTML

      
      

      JavaScript

      (function($) {
          var infoModal = $('#myModal');
          $('.thumbnail').on('click', function(){
              $.ajax({ 
                type: "GET", 
                url: 'getJson.php?id='+$(this).data('id'),
                dataType: 'json',
                success: function(data){ 
                  htmlData = '
      • title: '+data.first_name+'
      • age: '+data.age+'
      '; infoModal.find('.modal-body').html(htmlData); infoModal.modal('show'); } }); return false; }); })(jQuery);

      Method 2: using hidden div

      No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal

      HTML

      
      

      JavaScript

      (function($) {
          var infoModal = $('#myModal');
          $('.thumbnail').on('click', function(){
              htmlData = $(this).find('.profile').html();
              infoModal.find('.modal-body').html(htmlData);
              infoModal.modal('show');
              return false;
          });
      })(jQuery);
      

      0 讨论(0)
    提交回复
    热议问题