简体   繁体   中英

Text links in ajax WITHOUT Jquery

I have a slew of normal text links, and I want to be able to click them and send an ajax request to fetch the page, so I can dynamically load it into a different part of the parent page when I receive the html back from the server. Because I am stubborn and like to know how things are done the hard way, I don't want to bother with jquery. I want to do this the sledgehammer way. But I can't find any comments on how to handle links with ajax not using JQuery. I am a huge newb with all of this I would appreciate your help.

One suggestion is to attach a click handler to the link element and subvert the default behavior, eg

<div id="links_container">
    <a href="http://example.com/page" class="ajax_link">Page</a>
    <!-- etc -->
</div>

and in JavaScript..

// define the click handler
var ajaxLinkHandler = function(e) {

    e.preventDefault();// prevent browser from following link
    var link = e.target;
    var url = link.href;

    // I won't take the time to rehash standard JS AJAX here
};

// now attach the handler
var container = document.getElementById("links_container");
var ajaxLinks = container.getElementsByClassName("ajax_link");

for (var i=0; i < ajaxLinks.length; i++) {
    ajaxLinks[i].onclick = ajaxLinkHandler;
}

I like this approach because your HTML doesn't become hokey.

  • For AJAX in pure JS, see MDN .

You'll need to look up some of the following

In essence, select your <a> tag, add a click event to it. Prevent that click event triggering the link's default behaviour. Have the event fire an AJAX request to the page your link points to. Set the innerHTML of some element on the page to the contents returned by AJAX. You'll also probably need to parse out certain tags returned via ajax (the <head> for example).

In terms of the actual ajax request it'll look something like this:

//Taken (with modifications) from https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

/**
 * 'standard' way
 */
if (window.XMLHttpRequest) {
    httpRequest = new XMLHttpRequest();
}
/**
 * IE way
 */
else if (window.ActiveXObject) { // IE
    try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {}
    }
}

if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
}

function testFunction(data) {
    alert(data);
}

httpRequest.onreadystatechange = testFunction;
httpRequest.open('GET', url);
httpRequest.send();

Use the javascript XMLHttpRequest object. http://www.w3schools.com/ajax/ajax_xmlfile.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM