简体   繁体   中英

call function in views.py from jquery

I have def main(request) in views.py Wanna to make endless scrolling.

How can i call this func from jquery in my template:

    <script>
$(window).scroll(function () {
      if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        //call main
      }
    });
  </script>

In urls.py you have to add the url that you will be calling. It could be something like:

url(r'^call-main/$', views.call_main, name='call-main')

And then the ajax call from the function that you wrote:

$.ajax({
    url: "{% url 'call-main' %}",
    type: "POST",
    data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
    success: function () {
        // something here on success
    },
    error: function () {
       // something here on error
    }
});

Add your URL in urls.py

urlpatterns = [url(r'^sample/$', main, name='main_view')]

then use URL in the template

https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#url

{% url main_view %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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