jjery元素与django形式

时间:2017-08-24 18:36:15

标签: javascript jquery python ajax django

我正在使用用户可以拖放的jquery元素。我使用ajax将元素的顺序发布到django。

在django视图中,我能够处理从ajax发布的数据。

Django观点:

#this is the view where the jquery elements are being ordered by the user
def inside_exam(request):


    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
           #here I am able to retrieve the data from ajax and save it to a django model, code not shown here

           return redirect('exam_results')


#the view redirected to from the inside_exam view
def exam_results(request):

    #here I set the score for the exam and set the context, code not shown here 

    print(“all is set”)
    return render(request, 'quizresults.html', context)

执行打印(“all is set”),我可以在浏览器中打印quizresults.html的html。终端窗口中没有错误,这显示在终端中:“GET / exam_results / HTTP / 1.1”200 8981。

但是仍然显示相同的模板,它没有显示quizresults.html模板。知道为什么渲染(请求,'quizresults.html',上下文)没有按预期工作?

顺便说一下:当我使用没有jquery的django表单时,一切正常,并显示了quizresults.html模板。

由于我想向用户显示另一个模板,但不更新当前模板,在这种情况下,ajax可能不是发送jquery数据的正确方法吗?如果没有,那会是更好的方式吗?

编辑,ajax代码:

function dataToSend() {
    {% load static %}
     var node2 = document.getElementById('sortable');
     var idsInOrder = $("#sortable").sortable('toArray');
     console.log("the ids");
     console.log(idsInOrder);

     var fd = new FormData();
     for(var i=0; i<idsInOrder.length; i++) {
          j = i+1
          fd.append('a'+j, idsInOrder[i]);
     }

     $.ajax({
       type: 'POST',
       data: fd,
       cache: false,
       processData: false,
       contentType: false
     }).done(function(data) {
       //The data from the quizresults.html template is printed out here, but that template is not shown, the template in the browser is still the insidequiz.html template.
       console.log("the data");
       console.log(data);
     });
 }


 window.onload = function init() {
     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;
     }

     var csrftoken = getCookie('csrftoken');

     function csrfSafeMethod(method) {
         return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
     }
     $.ajaxSetup({
         beforeSend: function(xhr, settings) {
             if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
             }
         }
     });
};

2 个答案:

答案 0 :(得分:1)

在Django中使用redirect快捷方法会将HttpResponseRedirect对象返回给AJAX,它将作为302 Found状态代码处理,然后再向其发出请求。重定向资源并获取内容。即使您获得了内容,这似乎也不是正确的方法。

您可以使用方法exam_results执行其他工作并返回所需的上下文,该上下文将用于使用HttpResponse方法返回render对象。
然后,使用您获得的data,您可以将document替换为您收到的模板。

<强>解决方案

# views

#this is the view where the jquery elements are being ordered by the user
def inside_exam(request):
    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
           #here I am able to retrieve the data from ajax and save it to a django model, code not shown here

           context = exam_results(request)

           return render(request, 'quizresults.html', context)


# method to set the score for the exam
# return context from this method
def exam_results(request):

    #here I set the score for the exam and set the context, code not shown here 

    # build context
    return context


 # javascript

     $.ajax({
       type: 'POST',
       data: fd,
       cache: false,
       processData: false,
       contentType: false
     }).done(function(data) {
       //The data from the quizresults.html template is printed out here, but that template is not shown, the template in the browser is still the insidequiz.html template.
       console.log("the data");
       console.log(data);

       // replace the page with the new template
       var newDoc = document.open("text/html", "replace");
       newDoc.write(data);
       newDoc.close();

       // update the url
       window.history.pushState('', 'title', "newurl");
     });

参考:History API MDN

答案 1 :(得分:0)

我认为ajax在重定向方面会让事情变得复杂。我最终做的是创建一个HTML表单(隐藏),然后使用javascript将该表单发布到URL。不需要ajax。

HTML code:

 <form id="form1" action='{% url 'inside_exam' %}' method="post" style="display:none;">
   {% csrf_token %}
 </form>

 <p> <button type='submit' style="visibility" class="button button-long button-primary" onclick="sendData(this);">Send</button></p>

javascript代码:

function sendData() {
  var idsInOrder = $("#sortable").sortable('toArray');
  var form = document.getElementById('form1');    
  for(var i=0; i<idsInOrder.length; i++) {
      j = i+1
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", 'a'+j);
      hiddenField.setAttribute("value", idsInOrder[i]);

      form.appendChild(hiddenField);
  }
  console.log("form is:");
  console.log(form);

  form.submit();
}