我有一段代码在 Jquery 中进行加载并加载一个页面,加载该页面后我必须执行一些函数,但这些函数是在所有页面加载之前运行的,给我一个错误。
async function edit_matrix(id){
const response = await fetch(`http://127.0.0.1:8000/apps/edit/matrix/${parseInt(id)}`)
const data = await response.json()
if(data.determinant){
$(".cont").load("http://127.0.0.1:8000/apps/determinant");
console.log("JQuery")
$(document).ready(
select_grid(data.number_rows_a) //The code that must be executed after the load of the page
);
}else{
//another part of the code
}
}
我尝试添加await元素以使代码停止并在该操作结束之前运行,并且我尝试添加Jquery的准备方法,但它不起作用。
在load()中使用回调函数;
$(".cont").load("http://127.0.0.1:8000/apps/determinant", function() {
console.log("Content loaded!");
select_grid(data.number_rows_a); // Execute code after content is loaded
});
load()
,你会发现第二个参数是一个回调函数,它将在 AJAX 请求完成后执行。
因此,您可以将逻辑放在那里:
async function edit_matrix(id) {
const response = await fetch(`http://127.0.0.1:8000/apps/edit/matrix/${parseInt(id)}`)
const data = await response.json()
if (data.determinant) {
$(".cont").load("http://127.0.0.1:8000/apps/determinant", () => {
select_grid(data.number_rows_a);
});
} else {
// another part of the code
}
}