1

我试图在启动时从 javascript 填充选择框,每个框都取决于前一个框。

在 HTML 代码中我有

<body onload="start_up()">  
<span id="FirstList">xxxxxxx</span>  
<span id="SecondList">xxxxxxx</span>  

Javascript代码是

function start_up()
{
 load_select('','Type1')
 load_select(document.getElementById('select_first').value,'Type2')
}

function load_select(argument,code)
{
   xmlhttp=GetXmlHttpObject();
   if (xmlhttp==null)
       {
          alert ("Browser does not support HTTP Request");
          return;
       }
   var url="getdropdown.php";
   url=url+"?q="+code+argument;
   url=url+"&sid="+Math.random();  // this is needed to make sure its not loading a cached version
 last_http_type=code;
   xmlhttp.onreadystatechange=stateChanged;
   xmlhttp.open("GET",url,true);
   xmlhttp.send(null);
}

function stateChanged()
{
   if (xmlhttp.readyState==4)
    {
             if (last_http_type=="Type1")                      
                document.getElementById("FirstList").innerHTML=xmlhttp.responseText;
             else if (last_http_type=="Type2")
               document.getElementById("SecondList").innerHTML=xmlhttp.responseText;
             else if (last_http_type=="Type3")
               document.getElementById("OutputTable").innerHTML=xmlhttp.responseText;
             else if (last_http_type=="Type4")
               document.getElementById("OutputTable").innerHTML=xmlhttp.responseText;
             last_http_type="cleared";      
        }
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  return new XMLHttpRequest();   // code for IE7+, Firefox, Chrome, Opera, Safari
if (window.ActiveXObject)
  return new ActiveXObject("Microsoft.XMLHTTP");   // code for IE6, IE5
return null;
}

当它们的代码在 php 中生成时,选择框被命名为 select_first 和 select_second。

这适用于第一个,但第二个 load_select 失败,因为它不知道 select_first。我假设它是按顺序完成的,因此,当它到达语句时,应该知道第一个下拉菜单。(请注意,为了说明问题,上面的代码稍微简化了一点,load_select 的第二个参数确定了确切的 SQL 调用,而且 stateChanged 稍微复杂一些,因为它需要知道调用了哪个 load_select。但是,它们都可以正常工作他们自己,它在启动时的多重负载失败了。)

4

2 回答 2

0

所以基本上你是在进行两次连续的 AJAX 调用,并尝试将第二个的执行与第一个的结果联系起来?那样不行,因为 AJAX 中的第一个字母表示异步,意思是“好的,伙计们,我会去获取那个 url,但没有我你可以继续”。所以 javascript 触发第一个请求,然后更进一步,而不等待它返回一些东西。

如果您只想在成功执行第一个请求后运行第二个请求,那么您需要使用回调和onSuccess()事件。

为了使它更短,将第二个调用放在stateChanged()函数中。

于 2010-03-03T10:09:23.027 回答
-1

您应该将 javascript 与 html 分开编写。所以你的页面启动事件应该是

window.onload = function() {
    ....
    }
 or with jquery:
 $(function() { 
  ....
 });

所以你可以把你的其他函数和代码放在那里。这将是一个很好的使用 JQuery。查找示例加载方法。它可能比从头开始编写 ajax 更快地解决您的问题。

于 2010-03-03T09:52:31.613 回答