从django rest api上的ajax调用更新方法?

时间:2017-12-20 02:25:47

标签: ajax django django-rest-framework

有一个更新视图api用于更新员工的内容。我可以从django rest框架视图更新。 我正在使用jquery ajax进行更新,但它无法正常工作。

$(document).ready(function(){
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]);
            // Does this cookie string begin with the name we want?
            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) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}


$(".update-employee").submit(function(event){
      event.preventDefault()
      var this_ = $(this)
      var form =  this_.serializeArray()
      $.each(form, function(key, value){

      })
      var formData =  this_.serialize()
      console.log(formData);

var temp =
{
  "name": form[4].value,
  "email": form[1].value,
  "address": form[2].value,
  "phone_number": form[3].value,
  "username": {{ user_id }},
  "school": {{ school_id}},
  "language_id": {{ language_id }}

}

      $.ajax({
        url: "/api/student/{{ id }}",
        data: JSON.stringify(temp),
        beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  },

        method: "PUT",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function(data){
           console.log(data)


        },
        error: function(data){
          console.log("error")
          console.log(data.statusText)
          console.log(data.status)
        }
      })

    });
    });

temp变量使用值来更新通过视图中的上下文数据发送的值。 这里有什么问题,它在控制台中显示错误。

0 个答案:

没有答案