如何在页面加载时运行ajax jquery的第一个实例



我有一个jquery和ajax,它执行查询并在单击按钮时显示一个表。问题是,当页面第一次加载时,查询不会运行,也不会显示任何内容,因此必须单击按钮才能开始显示查询结果。有没有一种方法可以在页面加载时运行查询?然后只需按下按钮。我的代码是:

$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned                
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>

提前感谢!

只需在元素上调用click()即可模拟单击。

$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned                
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>

您可以提取您在点击处理程序中调用的函数,并在ready中调用它。

$(document).ready(function() {
const displayContent = () => {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned                
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}
displayContent();
$("#display").click(displayContent());
});

最新更新