页面加载时如何运行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>


繁星点点滴滴
浏览 114回答 2
2回答

蓝山帝景

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

侃侃尔雅

您可以提取您在点击处理程序中调用的函数并在ready.$(document).ready(function() {&nbsp; const displayContent = () => {&nbsp; &nbsp; $.ajax({ //create an ajax request to display.php&nbsp; &nbsp; &nbsp; type: "GET",&nbsp; &nbsp; &nbsp; url: "genquery.php",&nbsp; &nbsp; &nbsp; dataType: "html", //expect html to be returned&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; success: function(response) {&nbsp; &nbsp; &nbsp; &nbsp; $("#responsecontainer").html(response);&nbsp; &nbsp; &nbsp; &nbsp; //alert(response);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; }&nbsp; displayContent();&nbsp; $("#display").click(displayContent());});
打开App,查看更多内容
随时随地看视频慕课网APP