![](/img/trans.png)
[英]How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
[英]How can i perform PUT request using ajax and jquery in Django?
我一直在努力尝试使用 PUT 请求更新 django 中的数据库。 我正在从表单中收集数据,并且想根据用户键入的文本更新数据库条目。 我特别必须使用 PUT 请求方法,但我不知道该怎么做。 任何帮助将不胜感激
在这里,我从表单中获取数据:
$("#modify-btn").click(function(){
console.log('modify pressed')
$.ajax({
url : "{% url 'modify item' %} ",
method : "POST",
data: $("#detailsForm").serializeArray(),
success : function (data) {
console.log(data.id,data.name,data.brand,data.model)
/////
$.ajax({ /// this is where i need to use the PUT request
url :
})
///
}
})
})
这是我的views.py 文件:
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.template import loader
from phonemodels.models import Phone
def index(request):
return render(request,'phonemodels/index.html',{
'phones' : Phone.objects.all(),
})
def items_json(request):
return JsonResponse({
'phones' : list(Phone.objects.values())
})
def new_item(request):
phone_name = request.POST['Brand']
phone_model = request.POST['Model']
phone_price = request.POST['Price']
phone = Phone (brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price)
phone.save()
return JsonResponse({
'id' : phone.id,
'brand': phone.brandName,
'model' : phone.phoneModel,
'price' : phone.phonePrice
})
def modify_item(request):
phone_name = request.POST['BrandModify']
phone_model = request.POST['ModelModify']
phone_price = request.POST['PriceModify']
phone = Phone.objects.get(brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price)
phone.id
return JsonResponse({
'id' : phone.id,
'name': phone_name,
'brand': phone_model,
'model' : phone_price
})
403 是由 CSRF 异常引起的。
尽管如此,如果您想发出PUT
请求,它应该相当简单:
PUT
方法发送$.ajax
请求$.ajax({
url: '',
method: 'PUT'
})
PUT
请求,但您必须确保它使用csrf_exempt装饰器包装: path('your-url/', csrf_exempt(modify_item), name='modify-item-url')
我强烈建议您查看Django 的 CBV
我实际上遇到了同样的问题。 我不知道如何在 Django 中创建 PUT 请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.