ajax获取所有文章,如何将数据从AJAX文章获取到Django视图?

  • Post author:
  • Post category:其他


首先,您试图POST到一个html文件

url:”/utility_tool/decisions/solution_options/handsontable.html”,

相反,它应该是视图的url。

其次,ajax post请求的头部应该有csrftoken,您可以这样设置它:

// using jQuery get csrftoken from your HTML

var csrftoken = jQuery(“[name=csrfmiddlewaretoken]”).val();

function csrfSafeMethod(method) {

// these HTTP methods do not require CSRF protection

return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

}

$.ajaxSetup({

beforeSend: function (xhr, settings) {

// if not safe, set csrftoken

if (!csrfSafeMethod(settings.type) && !this.crossDomain) {

xhr.setRequestHeader(“X-CSRFToken”, csrftoken);

}

}

});

$.ajax({

url: “{% url ‘name of the view from urls.py’ %}”,

data: {

// here getdata should be a string so that

// in your views.py you can fetch the value using get(‘getdata’)

‘getdata’: JSON.stringify(hot.getData())

},

dataType: ‘json’,

success: function (res, status) {

alert(res);

alert(status);

},

error: function (res) {

alert(res.status);

}

});

在你的django看来:# views.py

from django.http import JsonResponse

def someView(request):

if request.method == ‘POST’:

# no need to do this

# request_csrf_token = request.POST.get(‘csrfmiddlewaretoken’, ”)

request_getdata = request.POST.get(‘getdata’, None)

# make sure that you serialise “request_getdata”

return JsonResponse(request_getdata)

在你的网址中:# urls.py

urlpatterns = [

# other urls

path(‘some/view/’, views.someView, name=’name of the view in urls.py’),

]