Search code examples
jqueryreplaceqtip

Find/replace some links in AJAX response


I'm using qTip to AJAX some content when a user hovers over glossary words on a site. Sometimes the AJAX response includes relative links to other files on the site. The problem is the links in the AJAX response try to resolve from the CURRENT page the user is on, not the page where the content was called from.

Example

User is on page <site>/topics/flying/missTheGround.html. There's a glossary term the user hovers over and an AJAX call is made and pulls content from <site>/glossary.html. The AJAX response has relative links to another file in the site, say, topics/swimming/drownLess.html. When clicking the link in the AJAX response, it tries to resolve FROM the current page, resulting in: <site>/topics/flying/topics/swimming/drownLess.html.

How can I modify the AJAX response? There are 2 things I need to modify:

  1. Local anchor links in the response need to redirect the user from the current page to the glossary page (pointing to the right target).
    • Find an href that starts with "#" and append a string that changes the local target link to be a link to <site>/glossary.html#<whatever the link target was>.
  2. Relative links in the response need to redirect the user from the current page to the correct location of the linked page.
    • Find an href that starts with "topics" and append a string that changes the target to absolute (from root) <site>/topics/running/goFast.html

My AJAX code:

content: {
    text: 'Loading...',
    ajax: {
        url: '<local file> #' + $(this).text().toLowerCase(),
        success: function (elems) {
            if (elems.length) {
                this.set('content.text', elems);
                var $elems = $(elems);
            } else {
                this.destroy();
            }
        }
    }
},

Solution

  • You can do two replaces as follows.

    Do the glossary replace:

    var glossaryUrl = "<mysite>/glossary.html";
    $(elems).find('a[href^="#"]').each(function(i, link) {
        var originalLink = $(link).attr('href');
        $(link).attr('href', glossaryUrl + originalLink);
    });
    

    Do the topics replace:

    var topicsUrl = "<mysite>/";    // The trailing forward slash is important
    $(elems).find('a[href^="topics"]').each(function(i, link) { 
        var originalLink = $(link).attr('href');
        $(link).attr('href', topicsUrl + originalLink);
    });