使用ajax使用数据库中的数据刷新Div

时间:2011-11-29 19:23:20

标签: jquery

我有这个项目,我在幻灯片中更改图像而不刷新页面。我花了4个多小时谷歌搜索教程是徒劳的。

我是ajax和jquery的新手,我想要一些东西开始。

我感谢任何帮助。谢谢:))

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery设置任何src标记的img属性:

$('#imgid').attr('src','new/path/to/image.jpg');

或者,也许.load就是您所需要的 - 它对HTML文档或片段执行AJAX请求,并自动将其添加到您选择的DOM元素中。例如:

$('#box1').load('images/photo.html')

将该URL的文件添加到ID为“box1”的DOM元素中。

答案 1 :(得分:0)

以上答案应解决您的疑问, 但是,如果您担心缓存图像,因为上述技术可能无法及时解析图像。尝试使用这个

从ajax调用接收的数据是

形式的JSON对象
data:
{
    "title":"Heart of Baikal",
     "url":"http://abc.net/4.jpg"
}

快速解释代码的作用

  1. 在从ajax调用中获取数据时,会创建一个javascript对象并将其推送到数组/列表中。
  2. 当您将鼠标悬停在目标上时,悬停功能只显示图像(使用此处显示的课程定义)
  3. 此处的链接提供了一个工作model的示例:

    $.ajax({
       //...add other properties of the ajax call here
       success: function(data) {
            var preloadedImages = [];
            $.each(data, function(index, item) {
                var tempImage = new Image();
                tempImage.src = item.url;
                preloadedImages.push(tempImage);
            });
            $(".show").hover(function() {
                //mouseover
                $.each(preloadedImages, function(index, item) {
                    $("<img>").attr({
                        src: item.src
                    }).appendTo("#ajax-json");
                });
            }, function() {
                //mouse out
                $("#ajax-json").empty();
            });
    
        },
    
        error: function(error) {
            alert("there was an error");
        },
        dataType: "json"
     });