combine multiple similar AJAX codes
I have the below code that goes with my site navigation. Since most of the code is the same I was wondering if there was a way to condense this. I'm super new to AJAX. Thanks
function web()
{
if(XMLHttpRequestObject) {
var obj = document.getElementById('content');
XMLHttpRequestObject.open("GET", "./nav/web.html");
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
functi开发者_Go百科on prices()
{
if(XMLHttpRequestObject) {
var obj = document.getElementById('content');
XMLHttpRequestObject.open("GET", "./nav/prices.html");
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
function clientList()
{
if(XMLHttpRequestObject) {
var obj = document.getElementById('content');
XMLHttpRequestObject.open("GET", "./nav/clientlist.html");
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
Yes you can, instead of having a function to each process, have built in a "template" that will hold every request, and then pass a variable to use like
switch(b) { case "web" : XMLHttpRequestObject.open("GET", "./nav/web.html"); break; case "prices" : XMLHttpRequestObject.open("GET", "./nav/prices.html");
here is a sample
function dameloPapa(a,b,c) {
if (a=="")
{
document.getElementById(c).innerHTML="";
return;
}
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(c).innerHTML=xmlhttp.responseText;
}
}
switch(b){
case "web" : XMLHttpRequestObject.open("GET", "./nav/web.html?id"+a); break;
//etc...
}
xmlhttp.send();
This way you only call in your code using JavaScript (onclick, onchange, etc) dameloPapa('variable','op','div_id'); and show results on
I optimized one like this to be call upon anytime that I want, I mix a lot this with PHP, MySQL and works like a charm, hope this helps!
精彩评论