php – 使用Ajax一次填充两个下拉列表
发布时间:2020-12-13 17:41:36 所属栏目:PHP教程 来源:网络整理
导读:我有三个 HTML DropDownList( select option / option / select).第一个DropDownList包含类别,第二个包含不同产品的子类别,第三个包含品牌(或制造商). 选择类别时,应根据传递给Ajax函数的类别ID,从数据库中一次填充两个下拉子类别和品牌.我正在使用以下Ajax
我有三个
HTML DropDownList(< select>< option>< / option>< / select>).第一个DropDownList包含类别,第二个包含不同产品的子类别,第三个包含品牌(或制造商).
选择类别时,应根据传递给Ajax函数的类别ID,从数据库中一次填充两个下拉子类别和品牌.我正在使用以下Ajax代码. function ajax() { if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp = new ActivexObject("Microsoft.XMLHTTP"); } } function getBrandList(selected) //selected is the category id. { ajax(); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("brandList").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax/BrandAjax.php?selected="+selected,true); xmlhttp.send(); alert(selected); } function getSubcategoryList(selected) //selected is the category id. { getBrandList(selected); //First above function is invoked to populate brands. ajax(); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("subCategoryList").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax/SubCatAjax.php?selected="+selected,true); xmlhttp.send(); } 选择类别时,将调用getSubcategoryList(选定)Javascript函数来执行Ajax请求.问题是我需要立即填充子类别和品牌下拉(当选择一个类别时). 它正在工作,并且根据传递的类别ID一次填充下拉列表(它是所选上述函数的参数). 我不必要地使用函数getBrandList()底部的警告框.注释此警报框时,只会填充一个子类别的下拉列表.品牌仍然是空的.我不再需要这个警报框了. 为什么会这样?解决办法是什么? 解决方法
seriyPS基本上达到了目标.问题实际上是xmlhttp变量.您需要在每个正在使用的函数中声明它是本地的.基本上,为函数调用创建一个闭包.然而,问题不一定是它需要“本地”,而是作为全局变量在第二个请求中重新定义.这基本上会终止初始请求,因为变量现在指向第二个请求.
警报框使其工作的原因是因为第一个请求正在完成ajax请求,然后才能“单击”确定. (警告框将暂停javascript执行,因此延迟第二个请求,直到您单击确定.) 要解决此问题,您可以修改代码以为每个请求使用不同的变量.尝试将您的功能更改为以下内容: // Global Variables var brandListRequest; var subcategoryRequest; function ajax() { var xmlhttp; //!! if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp = new ActivexObject("Microsoft.XMLHTTP"); } return xmlhttp; //!! } function getBrandList(selected) //selected is the category id. { brandListRequest = ajax(); //!! brandListRequest.onreadystatechange=function() { if(brandListRequest.readyState==4 && brandListRequest.status==200) { document.getElementById("brandList").innerHTML=brandListRequest.responseText; } } brandListRequest.open("GET",true); brandListRequest.send(); //alert(selected); } function getSubcategoryList(selected) //selected is the category id. { getBrandList(selected); //First above function is invoked to populate brands. subcategoryRequest = ajax(); //!! subcategoryRequest.onreadystatechange=function() { if(subcategoryRequest.readyState==4 && subcategoryRequest.status==200) { document.getElementById("subCategoryList").innerHTML=subcategoryRequest.responseText; } } subcategoryRequest.open("GET",true); subcategoryRequest.send(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |