动态替换div容器内的数据

时间:2015-10-04 08:56:49

标签: javascript jquery html ajax

在DIV容器内动态加载数据的最佳方法是什么?

我们说我在页面上有很多图片。单击图片会在屏幕上打开DIV容器(无页面刷新),其中包含该图像的所有注释。

目前我正在发送一个AJAX请求,以便从数据库加载注释并在另一个页面中回显它们。然后我将这些数据与jQuery一起添加到DIV容器中。单击另一个图像将清除容器,并通过新的AJAX请求加载新数据。

在我看来,这可能不是最有效的方式,因为如果用户来回点击页面上的图像,则必须每次都重新加载数据。

我看到facebook每次选择新图像时都会更改网址。那么他们可能会使用URL中的ID来加载数据而不发送AJAX请求?

可能一旦加载了数据并选择了另一个图像,最好只隐藏页面上的旧图像注释而不是丢弃它们?那么如果再次点击图像,则不需要重新加载其数据?

3 个答案:

答案 0 :(得分:0)

如果您重新指定< img> -Tag里面有一些div,所以你做完之后会加载图片。如果您指定相同的图片两次或更多次,则该图像已经在大多数浏览器的缓存中。那你为什么可以做像

这样的事情

$(' #divid')。html('< img src =" ...">');

如果你想预先加载你的照片,我会把一些图像放到一些非常小的div中。如果你将图片放入一个隐藏的容器中,一些浏览器就不会预装它们。

如果您将图片存储到某个数据库或内存缓存中,请使用缓存标头。你可以编写一些outputpicture.php?id = 12345。 在那种情况下像

header('Content-Type: '.get_img_type($data));
header('Content-Length: '.strlen($data));
header("Pragma: public");
$expires = 60*60*24*14;
header("Cache-Control: maxage=".$expires);
header("Last-Modified: Mon, 26 Jul 1984 05:00:00 GMT");
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');

可以帮助很多。

答案 1 :(得分:0)

您可以在javascript对象中添加获取地址,并在每次发出ajax请求时映射加载到其中的内容。
然后,当用户点击图像而不是发送ajax请求时,首先检查对象中是否有该请求从那里加载,如果您没有对象中的地址,那么您可以继续并发送ajax请求并将其结果保存到我提到的对象。

答案 2 :(得分:0)

以下是关于如何避免对同一图像进行频繁/重复的ajax请求的想法。

假设您有一个在div中绘制注释的功能,它可以从服务器中获取响应,例如:

function displayComments(resp) {
    //Do stuff
}

让我们假设图像点击的ajax调用如下所示。

//We're probably better of using the wrapper (class/ID) of images to
//delegate events since setting/unsetting data may cause problems
//if we'd used bind on images directly
$("imagesContainerSelector").on("click", "img", function() {

    var $this = $(this);

    //See if comments have already been fetched previously.
    //If yes, we'd have stored them as that image's data and 
    //we'd now simply use that data to display the comments.
    if ( $this.data("comments") ) {

        displayComments($this.data("comments"));
    } else {
        //We've not fetched comments for this image yet, so, fetch it
        $.ajax({
            url: '...',
            data: '...'
            //more options
        }).done(function(data) {
            //When done, display comments
            displayComments(data);
            //Set the resp as data for later use
            $this.data("comments", data);
        });
    }
});