简体   繁体   English

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

[英]ajax jQuery auto reload data when browser page refresh

how can i use ajax jquery to autoreload data from selected field related data to input field?我如何使用 ajax jquery 将数据从选定的字段相关数据自动重新加载到输入字段? it's only working when i am using $("#id_books").change(function() ! but i want to load data when browser page refresh or on page load....它仅在我使用$("#id_books").change(function()时才有效!但我想在浏览器页面刷新或页面加载时加载数据....

create-form.html创建-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>

Try using $(document).ready() , which will fire on page load.尝试使用$(document).ready() ,它会在页面加载时触发。 eg:例如:

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

You'll most likely need to refactor your code as $(this).val();您很可能需要将代码重构为$(this).val(); won't work (as 'this' is no longer '#id_books')不起作用(因为“this”不再是“#id_books”)

I've not tested the following (but it should give you an idea), try the following:我还没有测试以下内容(但它应该给你一个想法),请尝试以下操作:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM