onClick的Javascript 2函数仅运行最后一个

时间:2011-06-08 08:46:30

标签: javascript onclick

使用AJAX时遇到问题。通过onclick事件调用的2个函数,发布每个值切换AJAX并返回两个div中的数据。如果只将一个功能放在一个onclick中。它运行良好。但是输入2,只运行最后一个 ajax2('".$data."','".$num2."');。问题出在哪儿?

echo "<a OnClick=\"ajax1('".$data."','".$num1."');ajax2('".$data."','".$num2."');\">" click </a>";

两个js代码,功能类似。只是功能号,处理页面和ruturn div不一样。

功能1

function ajax1(data,number) {
      HttPRequest = false;
      if (window.XMLHttpRequest) {
         HttPRequest = new XMLHttpRequest();
         if (HttPRequest.overrideMimeType) {
            HttPRequest.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) {
         try {
            HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      } 
      }
        var url = 'page1.php';
        var pmeters = "data=" + data + "&number=" + number;
        HttPRequest.open('POST',url,true);
        HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        HttPRequest.send(pmeters);
        HttPRequest.onreadystatechange = function()
        {
             if(HttPRequest.readyState == 4) 
              {
               document.getElementById("return1").innerHTML = HttPRequest.responseText;                 
              }
        }
   }

function2

function ajax2(data,number) {
      HttPRequest = false;
      if (window.XMLHttpRequest) {
         HttPRequest = new XMLHttpRequest();
         if (HttPRequest.overrideMimeType) {
            HttPRequest.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) {
         try {
            HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      } 
      }
        var url = 'page2.php';
        var pmeters = "data=" + data + "&number=" + number;
        HttPRequest.open('POST',url,true);
        HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        HttPRequest.send(pmeters);
        HttPRequest.onreadystatechange = function()
        {
             if(HttPRequest.readyState == 4) 
              {
               document.getElementById("return2").innerHTML = HttPRequest.responseText;                 
              }
        }
   }

1 个答案:

答案 0 :(得分:3)

将两个函数的第一行更改为var HttPRequest = false;。这使得httprequest对每个函数都是私有的。