I am sure this is a common question, but since I’m really new to Ajax I couldn’t figure out which solution is the best for me and how to execute this:
I have a page with several links, and a div in the middle of the page in which the output of the ajax request is shown.
By now I have successfully used this ajax function for one link:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","history.html");
xmlhttp.send();
}
However, I want to show different outputs based on the links clicked.
These are some of my links:
<li class="menu-item"><a href="#" onclick="loadXMLDoc()">Link 1 - History</a></li>
<li class="menu-item"><a href="#">Link 2 - Economics</a></li>
<li class="menu-item"><a href="#">Link 3 - Physics</a></li>
I want to get and show different html files based on the links clicked, But I don’t know how to execute it.
I guess it is done by passing parameters, but I don’t know what to do in order make it work.
In your case, you could do:
and:
And output a different thing on the server side, depending on the
qparameter. (or, do it in JS: if 1, open “page1.html”; if 2, open “page2.html”, etc.However, I’d suggest that you don’t reinvent the wheel, and use a JS library such as jQuery; it’s gonna make your life a lot easier. For example, with jQuery, you could just use the following:
This might look a bit foreign at first, but it’s much more convenient than what you have. Another highlight is that you can save yourself the
onclickattribute and the resulting mixture HTML and JS.If you only need to do a few stuff within a project, you save yourself several kilobytes and use single-task libraries from http://microjs.com/# .