[英]How can I make sure ajax/jquery calls finish before an html page loads?
$(function() {
var $items = $('#items');
$.ajax({
type: "GET",
url: 'some-url',
data: {},
success: function(items) {
$.each(items, function(i, item){
item_polys.push(item.polygon);
$items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
});
localStorage.setItem('item_polys', JSON.stringify(item_polys));
},
// Error handling
error: function (error) {
console.log(`Error ${error}`);
},
});
I need 'item_polys' to be saved into local storage before my corresponding html page loads.在相应的 html 页面加载之前,我需要将“item_polys”保存到本地存储中。 I would also settle for a way to reload the html page just one time each time after it loads, so that it will populate correctly.
我还会选择一种方法,每次加载 html 页面后仅重新加载一次,这样它就会正确填充。 Thanks (and sorry if this has been answered already, I couldn't quite find what I was looking for when I searched)
谢谢(很抱歉,如果已经回答了这个问题,我在搜索时找不到我要找的东西)
Since you want the ajax request to occur when the user is on the exact same page that the populated elements will be in, I think the only good way of doing this would be to create or display the elements of the page dynamically.由于您希望 ajax 请求在用户与填充元素所在的页面完全相同时发生,我认为这样做的唯一好方法是动态创建或显示页面元素。 (This might be as simple as toggling a
display: none
on and off, but it depends on what the page is like and what you want.) (这可能就像切换
display: none
打开和关闭,但这取决于页面是什么样的以及您想要什么。)
So, make a function like populatePage
that shows the page, where the default state of the page is a loading screen (or blank, or whatever you want the user to see when the request is in progress).因此,制作一个
populatePage
来显示页面,其中页面的默认 state 是一个加载屏幕(或空白,或者您希望用户在请求进行时看到的任何内容)。 Maybe something like也许像
const populatePage = () => {
const items = JSON.parse(localStorage.items);
for (const item of items) {
$items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
}
$('main').show();
};
where main
is the container you want to show when things are ready, and that has styling that hides it by default.其中
main
是您想要在一切准备就绪时显示的容器,它具有默认隐藏它的样式。 Then:然后:
On pageload, check if the item exists in storage.在页面加载时,检查该项目是否存在于存储中。 If so, use it, and call
populatePage
immediately.如果是这样,请使用它,并立即调用
populatePage
。 Otherwise, have the page keep showing the loading banner or blank screen, make the ajax request, and call populatePage
when it's finished.否则,让页面继续显示加载横幅或空白屏幕,发出 ajax 请求,并在完成时调用
populatePage
。
$.ajax({
// ...
success: function (items) {
localStorage.items = JSON.stringify(items);
populatePage();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.