数据表:实时添加额外的行?
我试图在一个表加载后添加一个新行(因为我需要检索一些数据),但新行只显示’undefined’。 它看起来像这样:
$('#example tr').each( function () { id = this.id.substr(4); var result2; if (id.length > 0) { $.post('get_stuff.php', {id: id}, function(result) { result2 = result; }); oTable.fnOpen( this, result2, "info_row_"); } } );
上面打开新行并在其中写入“undefined”。 但是,如果在fnOpen调用之前添加alert(result2)
,结果将显示在警报中,然后写入该行。 我怎么解决这个问题?
您的$.post()
请求是异步的。
所以信息是在仍然被请求的时候写的。
你可以添加:
$.ajaxSetup({async:false});
在.post()
之前调用或使用带有async: false
选项的.ajax()
。
.post()
只是.ajax()
的简写版本
或者你可以在.post()
函数的成功回调中编写vakue。
$.post('get_stuff.php', {id: id}, function(result) { //result2 = result; // don't know if you still need the result2 var somewhere else. If that's the case you should use one of the other approaches (as stated above) oTable.fnOpen( this, result, "info_row_"); });
这将等到Ajax调用在执行函数之前连续完成。
$('#example tr').each( function () { id = this.id.substr(4); if (id.length > 0) { $.ajax({ url:'get_stuff.php', data: "id="+id, success: function(result) { oTable.fnOpen( this, result, "info_row_"); } }); } } );