I have recently started using ajax requests. I have the request working but it takes multiple seconds to load.
Code-
var x = 0;
function makeTR(){
var appendObject = "<tr>";
for(var i = 0; i < 3; i++){
$.ajax({
async: false,
type: 'GET',
url: domain + Players[x] + domain2,
success: function(data) {
appendObject = appendObject + "<td>" + makeTD(data.player, data.rank, data.guild_rank, data.fame, data.last_seen) + "</td>";
x++;
}
});
}
appendObject = appendObject + "</tr>";
return appendObject;
}
If you need anymore code I will give it to you, this is the only part where there is any real code though.
Sorry if there is another post out there, I looked for a while.
Thanks in advance!
As noted in a comment, your code is slow, because it performs the ajax requests one after the other, if each request takes a second, your function takes three. You need to embrace asynchronous code, and use promises and/or callbacks to make it work in parallel. Below is an example using promises.
// this function returns a 'promise'
function makeTr() {
var requests = []
// Don't use async: false, but collect the return values of $.ajax.
// Those are promises, which you can use in other calls.
for (var x=0; x<3; x++) requests.push($.ajax(domain + Players[x] + domain2))
// Wait until all promises are resolved, then perform the
// rendering function. The first return below returns a 'promise'
// of your 'appendObject'
return Promise.all(requests).then(function(allData) {
// allData is an array containing the results of your $.ajax
// calls now.
var appendObject = ""
for (var x=0; x < 3; x++) {
var data = allData[x]
appendObject += "<tr>"
....
appendObject += "</tr>"
}
return appendObject
})
})
Now you can call the function like that
makeTr().then(function(rows) {
$(...).append(rows)
})
But you better read up on promises and callbacks and asynchronous javascript in general. Because thats on of the best parts of javascript.
$.ajax({
type: 'GET',
cache : false,
url: domain + Players[x] + domain2,
success: function(data) {
appendObject = appendObject + "<td>" + makeTD(data.player, data.rank, data.guild_rank, data.fame, data.last_seen) + "</td>";
x++;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.