重用ajax功能

时间:2013-01-26 20:13:52

标签: javascript html ajax

我想重复使用这个功能但是我想每次都更改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();
    }

2 个答案:

答案 0 :(得分:2)

传入id作为函数的参数?

答案 1 :(得分:1)

您可以将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();
}
相关问题