jQuery:只能请求一次Ajax调用

时间:2013-02-19 15:32:26

标签: jquery ajax twitter-bootstrap

我正在使用以下代码在我的产品上显示“popover”效果。弹出窗口的内容来自Ajax。这是使用Twitter Bootstrap popovers。是否可以只进行一次Ajax调用?现在,每次我将鼠标悬停在产品上时,都会再次发送请求。我想调整这段代码,所以如果已经提取了内容,请使用它,不要再提出其他请求。

由于

$(document).ready(function(){
    //Quick view boxes
    var overPopup = false;

    $("a[rel=popover]", '.favorites').popover({
        trigger: 'manual',
        placement: 'bottom',
        html: true,
        content: function(){
            var div_id =  "div-id-" + $.now();
            return details_in_popup(div_id, $(this).data('product-id'));
        }

    }).mouseover(function (e) {
        // when hovering over an element which has a popover, hide
        // them all except the current one being hovered upon
        $('[rel=popover]').not('[data-unique="' + $(this).data('unique') + '"]').popover('hide');
        var $popover = $(this);
        $popover.popover('show');

        $popover.data('popover').tip().mouseenter(function () {
            overPopup = true;
        }).mouseleave(function () {
            overPopup = false;
            $popover.popover('hide');
        });

    }).mouseout(function (e) {
        // on mouse out of button, close the related popover
        // in 200 milliseconds if you're not hovering over the popover
        var $popover = $(this);
        setTimeout(function () {
            if (!overPopup) {
                $popover.popover('hide');
            }
        }, 200);
    });
});

function details_in_popup(div_id, product_id){
    $.ajax({
        url: 'index.php?route=product/product/get_product_ajax',
        type: 'post',
        data: 'product_id=' + product_id,
        dataType: 'json',
        success: function(json){
            if (json['success']) {
                $('#' + div_id).html(json['success']);
            }

        }
    });
    return '<div id="'+ div_id +'">Loading...</div>';
}

以下是我的html结构的样子:

<div class="image">
    <a data-unique="unique-3" data-product-id="39" rel="popover" href="link to product">
        <img src="path to image" />
    </a>
</div>

更新:

感谢大家的帮助和意见。以下是我修复它的方法:

function details_in_popup(div_id, product_id){

    //I added this block
    if ( $("#popover_content_for_prod_" + product_id).length ) {
        return $("#popover_content_for_prod_" + product_id).html();
    }

    $.ajax({
        url: 'index.php?route=product/product/get_product_ajax',
        type: 'post',
        data: 'product_id=' + product_id,
        dataType: 'json',
        success: function(json){
            if (json['success']) {
                $('#' + div_id).html(json['success']);

                //Also added this line
                $('body').append('<div style="display:none;" id="popover_content_for_prod_' + product_id + '">' + json['success'] + '</div>');
            }

        }
    });

    return '<div id="'+ div_id +'">Loading...</div>';
}

3 个答案:

答案 0 :(得分:1)

您可以随时修改ajax函数,将检索到的数据存储在data()的元素上,并在执行ajax调用之前检查是否存有任何此类数据。有点像“缓存”功能:

function details_in_popup(div_id, product_id){
    var data = $('#' + div_id).data(product_id);
    if ( data ) {
        $('#' + div_id).html(data);
    }else{
        $.ajax({
            url: 'index.php?route=product/product/get_product_ajax',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            success: function(json){
                if (json['success']) {
                    $('#' + div_id).html(json['success'])
                                   .data(product_id, json['success']);
                }

            }
        });
        return '<div id="'+ div_id +'">Loading...</div>';
    }
}

答案 1 :(得分:0)

只需使用全局布尔变量isFetched。 在Ajax请求之前检查isFetched,并仅在isFetched为false时执行请求。

var overPopup = false;
var isFetched = false;
var data = '';
$("a[rel=popover]", '.favorites').popover({
    trigger: 'manual',
    placement: 'bottom',
    html: true,
    content: function(){
        var div_id =  "div-id-" + $.now();
        if(!isFetched){
            data = details_in_popup(div_id, $(this).data('product-id'));
        }
        isFetched = true;
        return data;
    }

})

答案 2 :(得分:0)

使用隐藏元素存储boolean的值,并在AJAX调用之前获取它,然后在完成后设置它。

HTML:

<div id="hiddenElement" value="true" style="display:none; visibility:hidden;"></div>

JS:

var once = $("hiddenElement").val();

if (once) {
    $.ajax({
        type: "POST", 
        url: "ajax.php?action=add_driver", 
        dataType: "json",
        date:  $("form#addDriver").serializeArray(),
        beforeSend: function() {
            $('.error, .success, .notice').remove();
        }
    }).done(function() {
        $("#hiddenElement").val("false");
    });
}