我被困在这里,任何帮助都会受到赞赏。
我有一个项目列表框,我想通过AJAX(调用web服务)检索列表中每个项目的数据。需要根据调用的行来操作检索到的数据。 如果我传入row参数,则其值始终大于行数。 有没有办法传递ajax调用启动时的值?
var NumRows = list.options.length;
for ( var row = 0; row < NumRows; row ++ )
{
var Value = list.options[row].value;
var xmlHttpObj = CreateXmlHttpRequestObject();
if ( xmlHttpObj != null )
{
xmlHttpObj.open( "POST", "Async.ashx?arg1=GetPhysicalPathInfo&arg2=" + Value, true );
xmlHttpObj.onreadystatechange = function ( row )
{
// code that needs to know what row we were from
}
}
xmlHttpObj.send();
}
答案 0 :(得分:2)
创建一个具有自执行功能的闭包:
var NumRows = list.options.length;
for ( var row = 0; row < NumRows; row ++ )
{
!function(row) {
var Value = list.options[row].value;
var xmlHttpObj = CreateXmlHttpRequestObject();
if ( xmlHttpObj != null )
{
xmlHttpObj.open( "POST", "Async.ashx?arg1=GetPhysicalPathInfo&arg2=" + Value, true );
xmlHttpObj.onreadystatechange = function ()
{
// code that needs to know what row we were from
}
}
xmlHttpObj.send();
}(row);
}
当然,从循环中发出AJAX请求是一个重要的红旗。这非常低效;考虑进行一次调用并从服务器返回一个数组。