Unique URL for Article Viewer

2019-08-14 01:41发布

问题:

On my website, I have an Article Viewer page where users are allowed to search through and select articles to view. These articles are viewed in an Iframe. When an article is selected, I simply change the Iframe's src. Currently, there is no way to establish a direct link to a specific article.

For example, if I were to copy the URL of the page and view it on a different computer, the Article that was being viewed would not show. Instead, it would show the page with an empty Iframe. Is there a way that I can create unique URLs for these articles so that if I were to copy the URL, the same article will be displayed elsewhere?

This is my html code:

<input id="article-search-textbox" class="textbox" type="text" placeholder="Article Search"></input>
<iframe id="document-viewer" src=""></iframe>

Javascript code using Jquery UI Autocomplete (http://api.jqueryui.com/autocomplete/):

$(document).ready(function(){
    $(function(){
        $("#article-search-textbox").autocomplete({
            source: "/functions/article_search.php",
            delay: 800,
            select: function(event, ui){
                $("#document-viewer").attr("src", "/articles/" + ui.item.value + ".pdf");
            }
        });
    });
});

article_search.php accesses the database and returns all results that match the search string.

回答1:

An easy way of doing this is adding a hash in the url:

$(document).ready(function() {
    $(function(){
        $("#article-search-textbox").autocomplete({
            source: "/functions/article_search.php",
            delay: 800,
            select: function(event, ui){
                window.location.hash = ui.item.value; // <<< Hash
                $("#document-viewer").attr("src", "/articles/" + ui.item.value + ".pdf");
            }
        });
    });

    // And check if the entered url has a hash, to load the article at page loading.
    var hash = window.location.hash;
    if(hash.length) {
        $("#document-viewer").attr("src", "/articles/" + hash + ".pdf");
    }
});


回答2:

Try this (untested):

<!-- HTML -->
<iframe id="document-viewer"></iframe><br />
<a id="article_link" href="#"></a>


/* jQuery */
$(document).ready(function(){
$(function(){
    $("#article-search-textbox").autocomplete({
        source: "/functions/article_search.php",
        delay: 800,
        select: function(event, ui){
            var article_url = "/articles/" + ui.item.value + ".pdf";
            $("#document-viewer").attr("src", article_url);
            $("a#article_link").attr({"href": document.location.hostname+article_url,"target":"_blank"}).html(ui.item.value);

        }
    });
});
});