jQuery 回击按钮时记住ajax添加的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7956563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:31:15  来源:igfitidea点击:

Remember ajax added data when hitting back button

jqueryajax

提问by Niklas

I have a search page where every search result is added to the page with AJAX. This way I can let users search for e.g Led Zeppelin, then do another search for Metallicabut add it to the same result list as the previous search.

我有一个搜索页面,其中每个搜索结果都使用 AJAX 添加到页面中。通过这种方式,我可以让用户搜索例如Led Zeppelin,然后再次搜索Metallica,但将其添加到与先前搜索相同的结果列表中。

My problem is when a user clicks on a link to a record, then hits the back button, back to the search result.
FireFox (7)keeps the page as it looked when I left it, displaying the full result.
IE (7,8)and Chrome (15)on the other hand will display the page as it were before adding any search results with AJAX, as if it doesn't remember that I added data to it.

我的问题是当用户点击一个记录的链接,然后点击后退按钮,回到搜索结果。
FireFox (7)保持我离开时页面的样子,显示完整的结果。另一方面,
IE (7,8)Chrome (15)将在使用 AJAX 添加任何搜索结果之前显示页面,好像它不记得我向其中添加了数据。

Below is the code I use. I tried to add the location.hash = "test";but it didn't seem to work.

下面是我使用的代码。我试图添加location.hash = "test";但它似乎没有用。

// Add search result
$("#searchForm").submit(function (event) {
    //location.hash = "test";
    event.preventDefault();

    $.post($(this).attr('action'), $(this).serialize(),
    function (data) {
        $("tbody").append(data);
    });
});  

I don't need a back button that keeps track of changes on the search page, like stepping through each different search result as it was added. I just want the browser to remember the last search result when I hit the back button.

我不需要一个后退按钮来跟踪搜索页面上的变化,比如在添加时逐步浏览每个不同的搜索结果。我只希望浏览器在我点击后退按钮时记住上次搜索结果。

SOLVED
Changing to document.location.hash = "latest search"didn't change anything. I had to use the localStorageas Amir pointed out.

解决
更改为document.location.hash = "latest search"没有改变任何东西。我不得不使用localStorageAmir 指出的那样。

This goes into the rest of the jQuery code:

这进入了 jQuery 代码的其余部分:

// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
    if ('myTable' in localStorage && window.location.hash) {
        $("#myTable").html(localStorage.getItem('myTable'));
    }
}

// Save the search result table when leaving the page.
$(window).unload(function () {
    if (('localStorage' in window) && window['localStorage'] !== null) {
        var form = $("#myTable").html();
        localStorage.setItem('myTable', form);
    }
});

采纳答案by Amir Raminfar

You have a few options.

你有几个选择。

  1. Use localstorageto remember the last query
  2. Use cookies (but don't)
  3. Use the hash as you tried with document.location.hash = "last search"to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
  1. 使用localstorage记住上次查询
  2. 使用 cookie(但不要)
  3. 使用您尝试使用的哈希值document.location.hash = "last search"来更新 url。您将再次查看散列,如果已设置,则执行另一个 ajax 来填充数据。如果你已经完成了 localstorage 那么你可以缓存最后一个 ajax 请求。

I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible.

我会使用 localstorage 和 hash 解决方案,因为这就是某些网站所做的。您还可以复制和粘贴 URL,它只会加载相同的查询。这非常好,我会说非常方便。

I am curious to know why it didn't work. Update your answer so we can help.

我很想知道为什么它不起作用。更新您的答案,以便我们提供帮助。

回答by Julien Renier

Another solution is to use the facts that INPUT fields are preserved while using back button. So, I do like that :

另一种解决方案是使用在使用后退按钮时保留 INPUT 字段的事实。所以,我喜欢这样:

My page contains an input hidden like that :

我的页面包含一个隐藏的输入:

<input type="hidden" id="bfCache" value="">

Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:

动态加载 ajax 内容后,我将内容备份到隐藏字段中,然后再显示:

function loadAlaxContent()
{
    var xmlRequest = $.ajax({
            //prepare ajax request
            // ...
        }).done( function(htmlData) {
            // save content
            $('#bfCache').val( $('#bfCache').val() + htmlData);

            // display it
            displayAjaxContent(htmlData);
        });
}

And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.

最后要做的是在页面加载时测试隐藏字段值。如果它包含一些东西,那是因为使用了后退按钮,所以,我们只需要显示它。

jQuery(document).ready(function($) {

    htmlData = $('#bfCache').val();

    if(htmlData)
        displayAjaxContent( htmlData );
});

回答by jbabey

I believe you can use the hash section (after the # sign) to differentiate the page pre-ajax call and post-ajax call, that way the back button will take you to the post-ajax call version instead. Can you elaborate on why this solution did not work for you?

我相信您可以使用哈希部分(# 符号之后)来区分页面 pre-ajax 调用和 post-ajax 调用,这样后退按钮将带您到 post-ajax 调用版本。您能否详细说明为什么此解决方案对您不起作用?

This page may help:

此页面可能有帮助:

http://ajaxpatterns.org/Unique_URLs#Bookmarkable.2C_Linkable.2C_and_Type-In-Able

http://ajaxpatterns.org/Unique_URLs#Bookmarkable.2C_Linkable.2C_and_Type-In-Able

"Bookmarkable, Linkable, and Type-In-Able

window.location.hash makes the URL unique, so a user can bookmark it, link to it, and type it directly into their browser. window.onload ensures the bookmark is used to set state. Polling or IFrame ensure this will work even when the base URL (before the hash) is the same."

“可添加书签、可链接和可键入

window.location.hash 使 URL 唯一,因此用户可以将其添加为书签、链接到它,然后直接在浏览器中键入它。window.onload 确保书签用于设置状态。轮询或 IFrame 确保即使基本 URL(在哈希之前)相同也能正常工作。”