简体   繁体   English

如何在同一页面上从Django和Ajax获得多个发帖请求?

[英]How do I get multiple post requests from Django and Ajax on the same page working?

I have been banging my head over this all day long. 我整天都在头。 Nothing seems to be working. 似乎没有任何作用。 Here's my situation. 这是我的情况。

I have a Django form with two fields: redirect_from , redirect_to . 我有一个包含两个字段的Django表单: redirect_fromredirect_to There are two submit buttons to this form: Validate and Save . 此表单有两个提交按钮: ValidateSave When the page loads, Submit is hidden and only Validate is shown. 页面加载后,“ Submit被隐藏,仅显示“ Validate

So now, when the user fills the two fields and clicks Validate I used Ajax to confirm that both the fields are the same. 因此,现在,当用户填写两个字段并单击“ Validate我使用了Ajax来确认两个字段相同。 If they are, show the Save button. 如果是这样,请显示“ Save按钮。 Clicking the Save button should save the form to the database. 单击Save按钮应将表单保存到数据库。 I also put in an oninput listener so that after the Ajax call is made, if the user tries to change the data, the Save button is hidden again and he has to now evaluate it again. 我还放入了oninput侦听器,以便在进行Ajax调用后,如果用户尝试更改数据,则“ Save按钮将再次隐藏,他现在必须再次对其进行评估。

Apparently this is supposed to be easy with Ajax, but I'm finding it extremely difficult and frustrating. 显然,使用Ajax可以做到这一点很容易,但是我发现这非常困难且令人沮丧。 This is my code so far: 到目前为止,这是我的代码:

My Template: 我的模板:

form method="post">
        {% csrf_token %}
        {% include 'partials/form_field.html' with field=form.redirect_from %}
        {% include 'partials/form_field.html' with field=form.redirect_to %}
        <button id="submit" class="btn btn-lg btn-primary" type="submit" name="save" value="Save">Save</button>
        <button id="ajax_submit" class="btn btn-lg btn-primary" type="submit" name="ajax" value="Ajax">Validate</button>
    </form>


{% endblock %}


{% block extra_scripts %}
{{ block.super }}

<script type="text/javascript">

    $(document).ready(function() {
        $("#submit").hide()
    });

    $('#id_redirect_to').on('input', function(){
        $("#submit").hide()
    });


    console.log("hello")
    //For getting CSRF token
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);


                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                   }
                }
             }
        return cookieValue;
  }


    //For doing AJAX post

    //When submit is click
     $("#ajax_submit").click(function(e) {
         console.log("Clicked")


     e.preventDefault();

    //Prepare csrf token
     var csrftoken = getCookie('csrftoken');


    //Collect data from fields
     /*var email = $('#inputEmail').val();*/
     var redirect_from= $('#id_redirect_from').val();
     var redirect_to= $('#id_redirect_to').val();
     console.log("URL from and to is", redirect_from, redirect_to)
     /*var password = $('#inputPassword').val();*/


    //Send data
     $.ajax({
           url : window.location.href, // the endpoint,commonly same url
           type : "POST", // http method
           data : { csrfmiddlewaretoken : csrftoken,
           redirect_from : redirect_from,
           redirect_to : redirect_to
           /*password : password*/
     }, // data sent with the post request

     // handle a successful response
     success : function(json) {
     console.log(json); // another sanity check
     //On success show the data posted to server as a message
         if (json['redirect_success'] === 'true')
         {
             alert("They are the same!" +json['redirect_success'] +'!.' );
             $("#submit").show()
         }
         else
         {
             $("#submit").hide() //Maybe display some error message in the future!
         }
     },

     // handle a non-successful response
     error : function(xhr,errmsg,err) {
     console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
     }
     });
    });


</script>

{% endblock extra_scripts %}

My Views: 我的意见:

def edit_redirect(request, pk):
    if request.method == 'GET':
        red_url = MarketingRedirect.objects.get(pk=pk)
        data = {'redirect_from': red_url.redirect_from, 'redirect_to': red_url.redirect_to}
        form = RedirectEditForm(initial=data)
        return render (request, 'marketing_redirect/edit_redirect.html', {'form': form,
                                                                                       'redirect_from':  red_url.redirect_from})

    if request.POST['save'] == 'Save':
        form = RedirectEditForm(request.POST)
        if form.is_valid():
            red_url = MarketingRedirect.objects.get(pk=pk)
            data = form.cleaned_data
            red_url.redirect_from = data['redirect_from']
            red_url.redirect_to = data['redirect_to']
            red_url.save()
            return redirect('backend_redirect')

    if request.POST['ajax'] == 'Ajax':
        if request.is_ajax():
            redirect_from = request.POST.get('redirect_from')
            redirect_to = request.POST.get('redirect_to')
            if redirect_from == redirect_to:
                data = {'redirect_success': 'true'}
                return JsonResponse(data)
            else:
                data = {'redirect_success': 'false'}
                return JsonResponse(data)

I'm getting a 500: MultiValueDictKeyError at "'Save'" 500: MultiValueDictKeyError at "'Save'"收到500: MultiValueDictKeyError at "'Save'"

Could someone guide me in the right direction here? 有人可以在这里指导我正确的方向吗? Very new to ajax. 对ajax来说很新。

This is due to using the button click events and not a form submit to preform the Ajax call. 这是由于使用按钮单击事件,而不是通过表单提交来执行Ajax调用。 Ajax is not sending the button name attributes. Ajax没有发送按钮名称属性。 You will need to manually add the button 'name' parameter to the data sent via Ajax, like so: 您将需要手动将按钮“名称”参数添加到通过Ajax发送的数据中,如下所示:

data : { csrfmiddlewaretoken : csrftoken,
       redirect_from : redirect_from,
       redirect_to : redirect_to,
       action: 'ajax' 
}

The use this in your view to capture if the Ajax request has been received: 在您的视图中使用此函数来捕获是否已接收到Ajax请求:

if request.POST.get('action') == 'ajax':
    # do ajax stuff here

Also as good practice I would be use 'safer' naming conventions to in order to avoid confusion. 同样好的做法,我将使用“更安全”的命名约定以避免混淆。 Like possibly changing the 'ajax' to 'verify' etc... 像可能将“ ajax”更改为“ verify”等...

I forgot to mention you will need to remove the type="submit" from the Ajax button. 我忘了提到您需要从Ajax按钮中删除type="submit"

Hope this helps :) 希望这可以帮助 :)

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

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