django ajax

本文展示了如何在Django中使用AJAX进行GET和POST请求处理。通过`urls.py`设置路由,`views.py`定义视图函数,实现数据的接收与响应。在前端HTML中,利用XMLHttpRequest对象进行异步通信,动态更新页面内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index,name='index'),
    path('ajax',views.ajax,name='ajax')
]

views.py

from django.http import JsonResponse
from django.shortcuts import render
import json

def index(request):
    return render(request,'index.html')

def ajax(request):
    if request.method=='POST':
        # 把json转成字典
        data=json.loads(request.body)
        return JsonResponse(data)  # 返回字典
    elif request.method=='GET':
        data={'name':'zl'}
        return JsonResponse(data)  # 返回字典

index.html

send()的内容是字符串
xhr.response需要JSON.parse()才能当json使用

div=document.querySelector('div')

div.addEventListener('mouseover',function(){
	xhr=new XMLHttpRequest()
	xhr.open('GET','{% url 'ajax' %}')
	xhr.send()
	xhr.onreadystatechange=function(){
	    if(xhr.readyState===4 && xhr.status>=200 && xhr.status<300 ){
	        data=JSON.parse(xhr.response)
	        div.innerText=data.name
	    }
	}
})

div.addEventListener('click',function(){
	xhr=new XMLHttpRequest()
	xhr.open('POST','{% url 'ajax' %}')
	data={'name':'zhanglu'}
	// 转成字符串发送
	data=JSON.stringify(data)
	xhr.send(data)
	xhr.onreadystatechange=function(){
	    if(xhr.readyState===4 && xhr.status>=200 && xhr.status<300 ){
	        // 需要解析成json
	        data=JSON.parse(xhr.response)
	        div.innerText=data.name
	    }
	}
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值