网络编程
位置:首页>> 网络编程>> Python编程>> Django中的ajax请求

Django中的ajax请求

作者:回忆不说话  发布时间:2022-10-19 10:28:14 

标签:django,ajax

需求:实现ajax请求,在界面上任意地方点击,可以成功传参。

创建项目如下所示:

Django中的ajax请求

settings.py文件的设置,这次我们除了要注册app和设置templates文件夹的路径,还要多设置一下static的路径,代码如下:


STATICFILES_DIRS = [
 os.path.join(BASE_DIR,'static')
]

首先,先对界面做处理,设置高为100%,然后引入我们所需要的文件static代码如下:

Django中的ajax请求

然后我们根据需求,创建一个点击事件,实现ajax请求,代码如下:

Django中的ajax请求

最后我们在视图文件中判断是否为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)
]

Django中的ajax请求

进入页面之后,在body范围内随意点击,就可以得到这个ajax请求返回的数据。

来源:https://blog.csdn.net/qq_39138295/article/details/82669563

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com