Update page content with several Ajax calls that depends on output from previous call
I need to update page content with data from external php scripts called in specific order.
On the page there are a number of divs where I want to put data collected via a php script (getdata.php). Data is collected continuously over and over again since it changes.
The problem is that I need to get the data in the correct order since each call is dependent on the output from the previous call, so
first get data for div1 using getdata.php?id=1
reply will contain data1 plus xid
show data1 in div 1 and
get data for div 2 using getdata.php?id=xid (id from first call)
reply will contain data2 plus new xid2
show data2 in div2 and
get data for div 3 using getdata.php?id=xid2 (id from second call)
etc
The number of divs can vary on the page and so the no of calls can vary. The number of divs is "known" when page is loaded first time so it can be sent with the onload javascript call
Tried using XMLHttpRequest but can't get it to work synchronously
Also am not sure if that is a good idea since it will probably lock the browser if synchronous and it can take 10-15 seconds for each call
So I suppose the best solution would be to usa a standard asynchronous XMLHttpRequest in order to not lock the browser and then initiate the next call when readyState == 4 in onreadystatechange function, but how can I make this a loop?
开发者_开发技巧Please advise
You shouldn't use synchronous XMLHttpRequest. That will indeed make the browser UI unresponsive.
What you could do is call a new XMLHttpRequest within the success callback of the previous one. This is actually a common pattern for chaining Ajax requests, one after the other.
$.ajax({
type: 'GET',
url: '/getdata.php?id=1',
success: function (data) {
// update div 1 ...
$.ajax({
type: 'GET',
url: '/getdata.php?id=' + data.id,
success: function (data) {
// update div 2 ...
// and so on ...
}
});
}
});
Further to your comment below, this is one way to refactor the above such that you can repeat the process "recursively" for a number of times (determined when the page is loaded).
function callAjax (id, n) {
$.ajax({
type: 'GET',
url: '/getdata.php?id=' + id,
success: function (data) {
// update div
$(data.id).text(data.content);
// loop recursively
if (n > 0) callAjax(data.id, n - 1);
}
});
}
callAjax(1, 50); // this will start the process which will "loop"
// for 50 times. The id of the first request
// will be 1, and subsequent ones will be obtained
// from the previous request.
精彩评论