社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

如何在Django中使用ajax和jquery执行PUT请求?

cristian9804 • 5 年前 • 1636 次点击  

在这里,我从表单中获取数据:

        $("#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 : 
                    })



                    ///
                }
            })

        })

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
        })
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54928
 
1636 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Alex
Reply   •   1 楼
Alex    5 年前

403是由CSRF异常引起的。

尽管如此,如果你想 PUT 请求应该相当简单:

  1. 你在发送一个 $.ajax 方法请求 投入
$.ajax({
    url: '',
    method: 'PUT'
})
  1. 投入 在基于函数的视图中进行请求,但必须确保用 csrf_exempt 装饰工:
 path('your-url/', csrf_exempt(modify_item), name='modify-item-url')

我强烈建议你调查一下 Django's CBV