我遇到了一个问题,该函数应该在所有内容准备好后加载。 我有一个巨大的ajax调用1700行代码。
我的代码如何工作: php 文件从数据库中的 3 个表获取数据并将其转换为 JSON。我打开 JSON 文件并为 1 个数据库结果创建 1 个元素。
目前,我有大约 100 个结果,但在最后一步中我将有大约 1000 个结果。因此,我创建了在加载页面之前放置的加载。但是因为主要内容是由js创建的,有时我的加载会在内容加载之前淡出1-2秒。我可以使用js或jquery。现在,我使用了类似的东西:
$(window).on ('load', function (){
setTimeout(function (){
$("#loading").fadeOut('slow');}, 1000)});
最佳答案
通过 AJAX 收到数据后执行该函数。检查下面的代码片段
$.ajax({
url: '/URL/TO/CODE',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //This is optional if you are using x-csrf-token validation of if u want to pass any header data
},
type: "post",
data: {
data:data //In case if you need to pass any data
},
dataType: 'json',
cache: false,
before:function(){
//Is you want to show any loader or anything while ajax is being executed.
},
success: function (response) {
//Once your ajax is success you can call your custom function to do things with the data
myCustomFunction();
},
error: function (res) {
console.log(res);
}
});
function myCustomFunction(){
//This to be executed when all data are filled by ajax and page is loaded
}
希望这有帮助。
关于javascript - ajax加载所有DOM元素后如何加载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52232485/