Load JSON data into a Bootstrap modal

前端 未结 1 872
长发绾君心
长发绾君心 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

      <ul>
          <li class="project span3" data-type="pfa">
          <a href="#" data-id="2" class="thumbnail">
              <img src="img/anon.jpg" alt="Kenneth Atkins" />
              <h1>Kenneth Atkins</h1>
              <p>[Description here]</p>
          </a>     
          </li>
      </ul>
      

      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 = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
                  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

      <ul>
          <li class="project span3" data-type="pfa">
          <a href="#" class="thumbnail">
              <img src="img/anon.jpg" alt="Kenneth Atkins" />
              <h1>Kenneth Atkins</h1>
              <p>[Description here]</p>
              <div class="profile hide">
                  <ul>
                      <li>title: Atkins Kenneth</li>
                      <li>Age: 16</li>
                  </ul>
              </div>
          </a>     
          </li>
      </ul>
      

      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)
    提交回复
    热议问题