如何解决选择国家时动态显示状态的问题

How to solve problems of dynamically display of state when a country is selected?

本文关键字:动态显示 状态 问题 国家 选择 何解决 解决      更新时间:2023-09-26

对于我正在进行的一个项目,我需要在用户选择其家庭成员的出生国家时动态检索特定国家的状态。我使用AJAX来实现这一点。

我只能提到7个家庭成员的详细信息,所以我的表单中有7个下拉列表用于家庭成员的国家和州。

每当用户选择一个特定的国家,一个javascript函数showState被调用(它存在于一个单独的.js文件中)。该函数有2个参数-一个是一个整数(位置),指定所选国家的字段位置(即是否为国家编号1,2,3等,直到7,以便相应的状态可以显示在状态字段- state1, state2, state3....)。第二个是从表单传递的国家名称。

该函数调用一个控制器,其中检索所选国家的状态。现在这些状态必须显示在表单中。但是状态并没有出现。

我的代码是:
var stateArr=["state1","state2","state3","state4","state5","state6","state7"];
function showState(place,str){
   -------
    var url="State1Controller";
    url +="?Country1=" +str +"&state=" +stateArr[place-1];
         xmlHttp.onreadystatechange = stateChange1;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
}
function stateChange1(){   
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){  
        document.getElementById(stateArr[place]).innerHTML=xmlHttp.responseText       
      }    
}

当我在文档中硬编码state1时。getElementByID,则得到所需的结果,否则得不到。请帮助。

这是因为变量place在函数stateChange1的作用域中未定义

试试这个。

var stateArr = ["state1", "state2", "state3", "state4", "state5", "state6", "state7"];
var p;
function showState(place, str) {
    //-------
    p = place;
    var url = "State1Controller";
    url += "?Country1=" + str + "&state=" + stateArr[p - 1];
    xmlHttp.onreadystatechange = stateChange1;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
function stateChange1() {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        // shouldn't we use 'p -1' instead of 'p' here also?
        document.getElementById(stateArr[p]).innerHTML = xmlHttp.responseText
    }
}

我相信您已经将表单中的字段命名为country1, country2等,并将相应的状态命名为state1, state2等。因此,如果用户在字段country1中选择一个国家,那么所选国家的州应该出现在字段state1中。我希望我答对了你的问题。

在这种情况下,您应该做的第一件事是检查您是否在函数中获得正确的值。使用showState函数中的alert(place)、alert(str)检查值。在stateChange1()函数中也使用alert(stateArr[place])。也可以在此函数中尝试alert(place)。

正如您所说,当您硬编码像state1这样的值时,此代码可以正常工作,我认为位置的值没有在stateChange1()函数中传递。您可以了解alert(place)是否将place的正确值传递给stateChange1()函数。如果适当的值没有传递,我认为这是问题,你可以编辑你的代码:

函数showState(地方,str) {

如果(地方= = 1){

    xmlHttp.onreadystatechange = stateChange1;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}else if(place==2){
    xmlHttp.onreadystatechange = stateChange2;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

}

函数stateChange1(){

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){  
    document.getElementById(stateArr[0]).innerHTML=xmlHttp.responseText       
}    

}函数stateChange2 () {
如果(xmlHttp。readyState==4 || xmlHttp.readyState=="complete"){
. getelementbyid (stateArr [1]) .innerHTML = xmlHttp.responseText
}}