Django中的ajax请求
作者:回忆不说话 时间:2022-10-19 10:28:14
需求:实现ajax请求,在界面上任意地方点击,可以成功传参。
创建项目如下所示:
settings.py文件的设置,这次我们除了要注册app和设置templates文件夹的路径,还要多设置一下static的路径,代码如下:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
首先,先对界面做处理,设置高为100%,然后引入我们所需要的文件static代码如下:
然后我们根据需求,创建一个点击事件,实现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)
]
进入页面之后,在body范围内随意点击,就可以得到这个ajax请求返回的数据。
来源:https://blog.csdn.net/qq_39138295/article/details/82669563
标签:django,ajax
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python内建类型int源码学习
2023-07-02 19:22:15
![](https://img.aspxhome.com/file/2023/0/59150_0s.png)
canvas 2d 环形统计图手写实现示例
2023-07-13 16:35:23
![](https://img.aspxhome.com/file/2023/1/55911_0s.jpg)
PHP解决高并发问题(opcache)
2023-11-07 23:17:49
![](https://img.aspxhome.com/file/2023/3/62033_0s.png)
基于asyncio 异步协程框架实现收集B站直播弹幕
2021-07-14 19:34:40
Python创建模块及模块导入的方法
2023-04-21 03:42:03
一篇文章搞懂Go语言中的Context
2024-04-26 17:16:05
![](https://img.aspxhome.com/file/2023/3/134393_0s.png)
python接口自动化(十七)--Json 数据处理---一次爬坑记(详解)
2021-10-03 08:39:35
![](https://img.aspxhome.com/file/2023/7/127657_0s.png)
Go语言io pipe源码分析详情
2024-01-31 00:21:46
SQL Server数据库中的表名称、字段比较
2024-01-13 17:02:24
![](https://img.aspxhome.com/file/2023/5/91185_0s.png)
python实现自动化上线脚本的示例
2021-02-01 05:14:49
jQuery打造动态下滑菜单
2010-04-20 14:50:00
![](https://img.aspxhome.com/file/UploadPic/20104/20/01-77s.jpg)
比较一下看看自己掌握了多少SQL快捷键
2009-01-04 14:04:00
python脚本后台执行方式
2021-02-12 20:57:58
Vue Socket.io源码解读
2024-06-05 15:28:35
![](https://img.aspxhome.com/file/2023/4/123144_0s.png)
python实点云分割k-means(sklearn)详解
2023-11-06 20:36:03
![](https://img.aspxhome.com/file/2023/0/96920_0s.jpg)
Python使用pymongo模块操作MongoDB的方法示例
2023-03-26 08:58:46
MySQL中的字符串模式匹配
2010-03-09 16:30:00
在vscode中启动conda虚拟环境的思路详解
2022-01-13 02:43:32
![](https://img.aspxhome.com/file/2023/9/87589_0s.png)
python语言time库和datetime库基本使用详解
2022-11-15 08:59:08
Django rest framework基本介绍与代码示例
2023-12-20 13:37:57