需求:实现ajax请求,在界面上任意地方点击,可以成功传参。
创建项目如下所示:
settings.py文件的设置,这次我们除了要注册app和设置templates文件夹的路径,还要多设置一下static的路径,代码如下:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
首先,先对界面做处理,设置高为100%,然后引入我们所需要的文件static代码如下:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html,body{
height:100%;
margin:0;
}
</style>
</head>
<body>
<script src="{% static 'jquery.js' %}"></script>
</body>
</html>
然后我们根据需求,创建一个点击事件,实现ajax请求,代码如下:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html,body{
height:100%;
margin:0;
}
</style>
</head>
<body>
<script src="{% static 'jquery.js' %}"></script>
<script>
$('body').click(function () {
// 参数1:请求的地址
// 参数2:回调函数回调函数的两个参数,1、服务器返回的数据,2请求的状态
// 新增参数2:url的参数必须为json类型
$.get('/ajax_get/',{'city':'郑州'},function (data,status) {
console.log('数据接收完毕')
alert(data.content)
})
})
</script>
</body>
</html>
最后我们在视图文件中判断是否为ajax请求,代码如下:
from django.shortcuts import render from django.http import HttpResponse,JsonResponse # Create your views here. def home(request): return render(request,'index.html') def ajax_get(request): # 判断当前请求方式是否为ajax if request.is_ajax(): city = request.GET.get('city') print(city) return JsonResponse({'content':"这是ajax请求"}) # return render(request,'index.html',{'content':'这是ajax请求'}) else: return JsonResponse({'content':"这是假的ajax请求"}) # return render(request, 'index.html', {'content': '这是假的ajax请求'})
启动服务器,刷新页面。
urls.py文件中代码设置如下:
from django.contrib import admin from django.urls import path from myApp import views urlpatterns = [ path('admin/', admin.site.urls), path('home/',views.home), path('ajax_get/',views.ajax_get) ]
进入页面之后,在body范围内随意点击,就可以得到这个ajax请求返回的数据。