JavaScript:获取两个不同值的dropdownlist选择的索引值

时间:2014-01-06 14:02:43

标签: javascript asp.net

我的页面中有一个下拉列表。当我提醒两个连续时间值的下拉选择索引时,我得到两个不同的值。这是我的代码。

$(document).ready(function() {
// here code for getting data from server to bind dropdown
DoAjaxCall("?method=getDataForDDL&callbackmethod=BindDDL")

// after binding data to dropdown I wrote following two alert
alert(document.getElementById("ddlState").selectedIndex); //this alert -1
alert(document.getElementById("ddlState").selectedIndex); // this alert 0
alert(document.getElementById("ddlState").selectedIndex); // this alert 0
}
function BindDDL(data, msg) {// this function is called automatically after   successfull AJAX call 
    var tbldata = eval('(' + data.toString() + ')'); //convert JSON data to Javascript Object
    var ddl = document.getElementById("ddlState");
    for (var i = 0; i < tbldata.Table.length; i++) {
        ddl.options[ddl.length] = new Option(tbldata.Table[i][1], tbldata.Table[i][0]);
    }
}
function DoAjaxCall(parameter){
 //code for getting data from server by "POST" method
 //After this function BindDDL is called which is call back function.
 }

1 个答案:

答案 0 :(得分:2)

AJAX请求是异步的,因此您无法在AJAX调用之后放置所选的索引检查代码;你必须把它放在AJAX请求的回调中。因此,有可能在第一次得到-1时,列表中没有填充任何数据,但第二次是。