我想构建一个图像滑块,显示每个项目的相关标题和详细信息的图像。需要从JSON中提取数据。例如,我存储了这样的图像。
items[
{
"image" : "images/item-1.png",
"heading" : "heading-1",
"text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
},
{
"image" : "images/item-2.png",
"heading" : "heading-2",
"text" : "Morbi tincidunt commodo scelerisque."
},
{
"image" : "images/item-3.png",
"heading" : "heading-3",
"text" : "Duis porttitor diam vitae leo elementum accumsan."
}
]
如何使用jquery / ajax执行此操作? 我是初学者,有人可以帮忙吗?谢谢你的时间。
答案 0 :(得分:1)
首先,它取决于您使用的滑块。 抽象方法就是这样的。
$(document).ready(function(){
getSlides();
})
function getSlides(){
var request = $.ajax({
type: "POST",
url: 'script.php',
data: {
action: "get_slilder_images"
},
dataType: "json"
});
request.done(function( response ) {
createSlides(response);
// fires on successfull reply
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
// fires on error
});
request.done(function() {
// fires everytime transaction completes with or withoute error
})
}
function createSlides(slides){
var container = $('#sliderContainer');
var html = '';
for(var i = 0; i < slides.length; i++){
html += '<li class="slide"><span class="slide-header">' + slides[i].heading + '</span><img src="' + slides[i].image + '"><span class="slide-text">' + slides[i].text + '</span></li>';
}
html = '<ul class="slide-list">' + html + '</ul>';
container.html(html);
container.someSliderPlugin(); // here it depends on what slider you use, most of them take a list as input.
}