且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery从URL加载动态div内容

更新时间:2023-02-23 19:39:38

当您重新加载页面时,缺少是因为它们不在文档源中;他们已经被添加到DOM以后。



我认为你有两种选择,第一种是我通常使用的。



当您执行搜索时,请将搜索条件或搜索结果存储在服务器上,以便在下一次呈现页面时,将结果与其一起呈现。我使用ASP.NET MVC 3并使用PartialView执行此操作。当我使用jQuery执行搜索时,它会导致服务器呈现相同的PartialView,并将结果HTML片段插入到结果div中。

或者,您需要激发当页面重新加载时,你的jQuery再次搜索。



重新提交搜索还是缓存结果***取决于搜索的成本和搜索结果的大小很可能是。

I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be and how can I solve this issue? I do not want to use any plug-ins either.

My jQuery code is:

$(document).ready(function () {
    $('[id^=type_]').click(function () {
        type = this.id.replace('type_', '');
        $('[id^=type_]').removeClass('selected');
        $('#type_' + type).addClass('selected');
        return false;
    });
    $('#type_search').click();
    $('#query').keyup(function () {
        var query = $(this).val();
        var url = '/' + type + '/' + query + '/';
        window.location.hash = '' + type + '/' + query + '/';
        document.title = $(this).val() + ' - My Search';
        $('#results').show();
        if (query == '') {
            window.location.hash = '';
            document.title = 'My Search';
            $('#results').hide();
        }
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            success: function (results) {
                $('#results').html(results);
            }
        });
    });
    var textlength = $('#query').val().length;
    if (textlength <= 0) {
        $('#query').focus();
    } else {
        $('#query').blur();
    }
});

When you reload the page, the reason that the results are missing is because they aren't in the document source; they've been added to the DOM later.

I reckon you have two choices, the first of which I generally use.

When you execute your search, have either the search criteria or the search results stored at the server so that when the page is next rendered, the results are rendered with it. I use ASP.NET MVC 3 and do this using a PartialView. When I use jQuery to execute the search, it causes the server to render the same PartialView and inserts the resulting HTML fragment into the results div.

Alternatively, you need to fire your jQuery search again when the page is reloaded.

Whether it's better to resubmit the search or to cache the results depends on how expensive the search is and how big the result set is likely to be.