2012-11-12 115 views
0

我有一个列表显示数据库中的一些信息,并且当您向数据库添加项目时,我希望列表更新。ajax每隔一次只更新

function getList(id) { 
    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById("list").innerHTML = xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("GET", "tool/getlist.php?q=" + id); 
    xmlhttp.send(); 
} 

function addItem() { 

    $.post('tool/addListItem.php', $("#addItem").serialize()); 
    var listID = $("#addItem").serializeArray()[0].value; 
    getList(listID); 
}​ 

的信息添加细,问题是,当我打电话从的addItem()中的GetList函数,什么都不会发生,如果我再次调用它,它更新了第一次,但随后的第三次没有任何反应和第四次更新。

我在更新之前用警报运行了一些调试。

var listID = $("#addItem").serializeArray()[0].value; 
alert(listID); 
getList(listID); 

如果我这样做,它点击确定后更新正常。

我对javascript和ajax总体来说还是比较新的,所以这可能是一个简单的错误,但它在过去的几个小时里一直让我发狂。

回答

1

要调用post和get是呼叫后已经做之前的工作,即在数据库将数据。 You need to call the getList in success of post,以便您从数据库中获取数据。阅读更多关于后here

$.post('tool/addListItem.php', $("#addItem").serialize()).success(function() {   
      getList(listID); 
}); 
+0

非常感谢你,这个伎俩。所以为了确保我理解了这个问题,基本上.success()会等待我所称做的任何函数? –

+0

是,请求成功时执行的回调函数。关于帖子的更多信息http://api.jquery.com/jQuery.post/ – Adil

0

尝试用这种

xmlhttp.open("GET", "tool/getlist.php?q=" + id,true);