3

In Django, how to click button on page without passing any value to view.py and then reloading current page? I have a button in the HTML:

<button type="button" class="btn btn-primary" id="refresh">refresh page</button>

I want to call a view in view.py, in which new HTML will be returned:

@csrf_exempt
def topology_show_refresh(request):
    '''topology refresh'''
    plan = {...}
    ...
    return render(request, 'topology_show.html', {'plan': plan})

The plan dictionary will be used in the new page.

    {% if plan.try == 'first' %}
        <script type="text/javascript">
            var max_lane_num = {{plan.max_lane_num}};
            var flag = 0;
        </script>
    {% else %}
        <script type="text/javascript">
            var max_lane_num = {{plan.lane_second}};
            var flag = 1;
        </script>
    {% endif %}

In my way, I use ajax to jump to this view, but I have no idea how to handle the return, e.g., pass the plan to HTML.

$(function(){
    $("#refresh").click(function(event){
        url = 'refresh/';
        $.post(url, {}, function(ret){
            //do something
            //how to pass "plan" dictionary to HTML
        });
    });
});
vinllen
  • 1,369
  • 2
  • 18
  • 36

1 Answers1

2

You are very close to the task of reloading page, Use 'location.reload(true)' instead of 'window.location.reload();'

And handle the response data by success() function. Try this :

    $(function(){
        $("#refresh").click(function(event){
            $.ajax({
             type: "POST",
             url: 'refresh/',
              success:function(response) {
              location.reload(true);

              //do something with 'response'
             }
            });
    });
Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35