Django - is_ajax() not returning true

女生的网名这么多〃 提交于 2021-02-08 09:11:59

问题


I know there are a lot of questions already asked on this but I am not able to get around with it. Please have a look:

from a profile view when "update" button is pressed I want the user to be displayed with an editable form with values picked from database. So as of now there is no POST data.

template:

<form id="shw-form" action="/update_user_profile/{{r_user.id}}" method="get" enctype="multipart/form-data">
<button type="submit" id="upd-btn"  class="btn btn-lg btn-warning" onclick="update_profile_page();">UPDATE</button>
</form>

jquery:

<script type="text/javascript">
    function update_profile_page() {


            var form = $("#shw-form");
            $("#upd-btn").attr('disable', 'true');
            $.ajax({
                url: form.action,
                type: 'get',
                success: function(response){
                    $("#upd-main").load(response); 
                }
                });

            return false;

    }
   </script> 

urls.py

url(r'^update_user_profile/(?P<user_id>\d+)$', 'myapp.views.update_user_profile', name='update_user_profile')

but when I click on the button the else part of is_ajax() is executed.

Please have a look if you can find anything that I am doing wrong or missing. Thanks.


回答1:


Don't use the onclick attribute of the button, it may not catch everything. Use jQuery's submit() event handler (http://api.jquery.com/submit/) instead.If you don't see any request in the console, then Daniel is very likely right: the form is submitted the usual way.




回答2:


is_ajax() checks X-REQUESTED-WITH header. Usually jQuery sets it properly. You can try to explicitly set this header in $.ajax:

$.ajax({
   url: form.action,
   type: 'get',
   success: function(response){
      $("#upd-main").load(response); 
   },
   headers: {
     'X-Requested-With': 'XMLHttpRequest'
   }
});

If this does not work, it means that your server or proxy strips this header.




回答3:


You're not disabling the default action of the button, so the form is getting submitted by the browser.

Since you've explicitly put the JS function in the HTML onclick, you can just do this:

<button ... onclick="update_profile_page();return false;"


来源:https://stackoverflow.com/questions/23955607/django-is-ajax-not-returning-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!