哈希 jquery 并调用 ajax



我正在考虑做一个图片库动态,我正在寻找一个类似于Facebook的解决方案,但使用url哈希。

我希望收到有关此类调用 ajax 的 dettails,以便在不刷新页面的情况下动态获取信息,这是做我正在寻找的正确方法吗?旧浏览器有问题?

<html>
    <head>
    //jquery.js
    </head>
<body>
    <!-- #nameimage is the name of the big image that will be loaded, 
    so this hash will be used for the call ajax. -->
    <a href="#nameimage1"><img src="url-thumb-image1"></a>
    <a href="#nameimage2"><img src="url-thumb-image2"></a>
    <a href="#nameimage3"><img src="url-thumb-image3"></a>
    <a href="#nameimage4"><img src="url-thumb-image4"></a>
    <div class="image-big"></div>
</body>
</html>

Jquery

$(document).on('click','a', function(){
         var hash = window.location.hash; // nameimage
         // very simple ajax
         BASE_URL = 'http://localhost/';
         $.ajax({
                type: "POST",
                url: BASE_URL + 'get_image',
                data: "name_image=" + hash,
                success: function(result) {
                    // print result on div
                    $('.image-big').html(result);
                },
                error: function(){
                    alert('Error on ajax call');
                }
            }); 
});

.PHP

<?php
    $name_image = $_POST['name_image'];
    $path = 'main_folder/image/';
    echo '<img src="'.$path.$name_image.'.jpg">';
    // and i can cache the results
?>

var hash = window.location.hash;//nameimage 需要查看锚标记的 href,此时窗口位置哈希尚未更新。

var hash = $(this).attr("href");

我认为您需要删除哈希:

var hash = window.location.hash.substr(1);

但也许哈希当时还没有定义。所以最好使用

$(document).on('click','a', function(e){ 
    var hash = e.currentTarget.href.substr(1)
    ...

最新更新