加载新页面而不刷新当前页面

时间:2019-12-10 08:27:23

标签: javascript jquery html ajax django-templates

这是我的代码... okay.html

{% extends "sch/base.html" %}
{% load staticfiles %}
{% block content %}
<div class="row" id="ada">
    <form action="" method="post">
       {% csrf_token %}
        <div align="center" class="container table-responsive mt-2" >
{% block scripts %}
{{ block.super }}
<script>
window.onload = function()
    {
        var button = document.querySelector('button');
        button.onclick= function(e)
            {
                e.preventDefault();
                addRecord()
            }
    }
    function addRecord() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ada").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "{% url 'add-advert' %}", true);
  xhttp.send();
}
</script>
{% endblock %}
            <div> <a href="javascript:;" onclick="addRecord()" ><button type="button" class="btn btn-primary"> Add New Advert </button></a></div>
    </form>
</div>
{% endblock %}

base.html

<!DOCTYPE html >
{%load staticfiles%}
{% load crispy_forms_tags %}
<html>
<head>
    <meta charset="UTF-8">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'style.css' %}"/>
    <title>{% block title %}{% endblock %}</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

</head>
<body class="container-fluid">
<div class="row">
<div class="col-lg-12">

    {% block content %}
    {% endblock %}

</div>
</div>
</body>
</html>

我是javascript新手。 我正在尝试在当前页面(okay.html)的div内加载另一个页面(广告)。它们都扩展了base.html。我也尝试使用$ .ajax,但是没有用。 有人告诉我添加第一个函数脚本,因为最初我是无法获取引用的,所以后来我试图寻找一种更好的方法来定义函数addrecord

3 个答案:

答案 0 :(得分:0)

我认为也许可以尝试在此处添加location.reload();

    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ada").innerHTML = this.responseText;
      location.reload();
    }
  };

答案 1 :(得分:0)

HTML

<div class="row">
        <nav role="navigation" class="nav">
            <a class="link1">Button</a>
       </nav>
</div>

Ajax

<script>
jQuery( ".link1" ).on( "click", function(e) {
    e.preventDefault();
    processAjaxData('about', '/home/about', 'about');
}
</script>

答案 2 :(得分:-2)

尝试使用 iframe 而不是 DIV。加载您的第二页