获取getXMLHTTP未定义错误

时间:2013-01-18 15:44:50

标签: ajax xmlhttprequest

这是我的javascript:

<script type="text/javascript"> 
function getState(countryId)
{
   var strURL="findState.php?country="+countryId;
   var req = getXMLHTTP();
     //ERROR is right here
     //UNCAUGHT REFERENCE ERROR: getXMLHTTP IS NOT DEFINED
   if (req)
   {
     req.onreadystatechange = function()
     {
      if (req.readyState == 4)
      {
      // only if "OK"
     if (req.status == 200)
         {
        document.getElementById('statediv').innerHTML=req.responseText;
     } else {
       alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
        }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}
</script>

这是从这个叫来的:

  <tr>
   <td width="150">Country</td>
   <td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option>       </select></td>
  </tr>

为了安全起见,这是我的标题,也许我这样做不正确?

<head>
    <link rel="stylesheet" type="text/css" href="view/css/application.css" />
    <script type="text/javascript" src="view/javascript/application.js" ></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>

另一个注意事项,我正在使用this示例,他正在使用mysql服务器,我使用ODBC连接到Access数据库。我不会为此使用xmlHTTP吗?我老实说不知道。

1 个答案:

答案 0 :(得分:3)

你的getXMLHTTP()应如下所示:

    <script type="text/javascript"> 
        function getXMLHTTP() {
           var x = false;
           try {
              x = new XMLHttpRequest();
           }catch(e) {
             try {
                x = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(ex) {
                try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1) {
                    x = false;
                }
             }
          }
          return x;
        }

        function getState(countryId){
          var strURL="findState.php?country="+countryId;
          var req = getXMLHTTP();

          if (req){
            req.onreadystatechange = function(){
              if (req.readyState == 4){
                if (req.status == 200){
                  document.getElementById('statediv').innerHTML=req.responseText;
                } else {
                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
              }
            }
            req.open("GET", strURL, true);
            req.send(null);
           }
        }
</script>