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 &amp;&amp; xhr.status&gt;=200 &amp;&amp; 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 &amp;&amp; xhr.status>=200 &amp;&amp; xhr.status<300 ){
	        // 需要解析json
	        data=JSON.parse(xhr.response)
	        div.innerText=data.name
	    }
	}
})

原文地址:https://blog.csdn.net/zhangludada/article/details/124285091

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_33214.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注