浏览器页面刷新时,ajax jQuery自动重新加载数据

时间:2020-09-08 21:56:16

标签: javascript html jquery ajax

我如何使用Ajax jQuery自动将数据从选定的字段相关数据重新加载到输入字段?它仅在我使用$("#id_books").change(function()时有效!但是我想在浏览器页面刷新或页面加载时加载数据。...

create-form.html

<select name="books" class="form-control" id="id_books">
  <option value="1" selected="">haxer</option>
  <option value="2">django</option>
  <option value="3">HCV</option>
  <option value="4">python</option>
  <option value="5">CBC</option>
</select>

<div class="form-group col-sm-2 text-center">
    <input class="form-control" type="text" name="price" id="priceData" readonly>
</div>
<script>
    $("#id_books").load(function () {
        var id = $(this).val();
        $.ajax({
            url: `http://localhost:8000/report/${id}`,
            data: { 'id': id },
            dataType: 'json',
            success: function (response) {
                if (response != null) {
                    $('#priceData').val(response.price);
                }
            }
        });
    });
</script>

1 个答案:

答案 0 :(得分:1)

尝试使用$(document).ready(),它将在页面加载时触发。例如:

$(document).ready(function() {
      alert("Page has loaded!");
});

您很可能需要重构代码,因为$(this).val();不起作用(因为“ this”不再是“ #id_books”)

我还没有测试以下内容(但是应该可以给您一个想法),请尝试以下操作:

<script>
     $(document).ready(function() {
        loadData()
    });

    $("#id_books").change(function () {
        loadData()
    });

    function loadData()
    {
        var id = $("#id_books").val();
        $.ajax({
            url: `http://localhost:8000/report/${id}`,
            data: { 'id': id },
            dataType: 'json',
            success: function (response) {
                if (response != null) {
                    $('#priceData').val(response.price);
                }
            }
        });
    }
</script>