Javascript 重用ajax函数

Javascript 重用ajax函数,javascript,html,ajax,Javascript,Html,Ajax,我想重复使用这个函数,但我想每次都更改id(在本例中为品牌),我是否需要每次都重新创建该函数,还是有其他方法 这就是功能: function showUser(str) { if (str=="") { document.getElementById("brand").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for

我想重复使用这个函数,但我想每次都更改id(在本例中为品牌),我是否需要每次都重新创建该函数,还是有其他方法

这就是功能:

        function showUser(str)
    {
    if (str=="")
      {
      document.getElementById("brand").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("brand").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","inc/form_rest.php?q="+str,true);
    xmlhttp.send();
    }

将id作为函数的参数传递?

将id作为函数的参数传递?

您可以将id作为参数传递

function showUser(str, id) {
    if (str=="") {
      document.getElementById(id).innerHTML="";
      return;
    }
    if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
    } else {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById(id).innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET","inc/form_rest.php?q="+str,true);
    xmlhttp.send();
}

您可以将id作为参数传递

function showUser(str, id) {
    if (str=="") {
      document.getElementById(id).innerHTML="";
      return;
    }
    if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
    } else {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById(id).innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET","inc/form_rest.php?q="+str,true);
    xmlhttp.send();
}

没问题。别难过,我一直都在做这样的事。在最激烈的时刻,简单的事情往往会逃过我们的视线。没问题。别难过,我一直都在做这样的事。在最热的时刻,简单的事情往往会逃过我们的视线。只有不到0.34%的互联网用户仍然使用IE5和IE6。摆脱
新的ActiveXObject
调用是安全的。不到
0.34%的互联网用户仍然使用IE5和IE6。摆脱
新ActiveXObject
调用是安全的。