我想加载一个 JSON 文件,该文件在 Bootstrap Modal 中创建一个列表。我已将其设置为如果您单击某个人的图片,就会弹出模态框。
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
这是 JSON 数据的示例:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
我希望模态框在框内显示类似这样的内容:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
我还想确保数据与图片相关联,以免模式混淆。如果这有点令人困惑,我很抱歉。如果有人有任何问题,我会尽力澄清。
最佳答案
方法一:使用Ajax
每次用户点击图片时,您都会从点击的图片中获取 ID,然后向服务器发送 Ajax 请求以获取 JSON 对象。
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);
方法二:使用隐藏div
无需任何 Ajax 请求,但您需要创建一个隐藏的 div,其中包含您要在模态中显示的所有信息
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);
关于javascript - 将 JSON 数据加载到 Bootstrap 模式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25464562/