开发者

jQuery: How to get return value of function as value of id attribute?

I'm trying to create a new tr element and set it's id attribute to the last id in the table of my MySQL db.

Here's what I have, but this does not set the id properly:

$('<tr>').html(response)
.attr('id',function(){开发者_C百科  
    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

How can I get this working right? The alert proves that my server side code is correct, it's just that the id attribute is not being created for the new row.


AJAX calls in Javascript are asynchronous, meaning that your code will not wait for the call to finish.

Therefore, your code is executing return daId before the server replies.

Thhe only good way to return a value from an AJAX call is to use a callback function, like $.get.

Although it is possible to make a synchronous AJAX call, it will completely freeze the entire browser until the server replies, so it is not a good idea.

In your case, you should probably only add the element after the AJAX call finishes (in the callback.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜