jQuery:如何获取函数的返回值作为id属性的值?

时间:2010-01-12 17:22:05

标签: jquery

我正在尝试创建一个新的tr元素,并将它的id属性设置为我的MySQL数据库表中的最后一个id。

这就是我所拥有的,但这并未正确设置ID:

$('<tr>').html(response)
.attr('id',function(){  
    var daId;
    $.get(
        '/getlastid.php',
        null,
        function(response){
            daId = response;
            alert(daId); //this shows correct id from db
        });
    return daId;
})
.prependTo('#table-id tbody'); //the tr does not have the id attribute set

我怎样才能正常工作?警报证明我的服务器端代码是正确的,只是没有为新行创建id属性。

2 个答案:

答案 0 :(得分:2)

Javascript中的AJAX调用是异步的,这意味着您的代码不会等待调用完成。

因此,在服务器回复之前,您的代码正在执行return daId

从AJAX调用中返回值的唯一好方法是使用回调函数,如$.get

虽然可以进行同步AJAX调用,但它会完全冻结整个浏览器,直到服务器回复,所以这不是一个好主意。

在你的情况下,你应该只在AJAX调用完成后添加元素(在回调中。

答案 1 :(得分:1)

  $.get(
        '/getlastid.php',
        null,
        function(response){
            daId = response;
$('#table-id tr:first').attr('id',daId);
//            alert(daId); //this shows correct id from db
        });