GET
def index(request):# 在url中获取学号sno = request.GET.get("sno", None)print("学号为:",sno)# 判断学号如果有值,执行查询if sno:results = get_student_by_sno(sno)# 展示在页面return render(request, 'index.html', context={'students': results})# 没有值,返回所有学生信息else:# 读取文件信息path = r"/Users/super/Desktop/杂记/王进/1/Project/Dj010801/student/static/files/Student.txt"students = read_student_from_file(path)# 加载HTML页面return render(request, 'index.html', context={'students': students})<script>$(function () {$("#getresult").on('click',function () {// 获取文本框内容sno = $('#sno').val();// 拼接查询字符串location.href = "{% url 'home' %}?sno=" + sno;});$("#getall").on('click',function () {location.href = "{% url 'home' %}";});});</script>
POST
提交数据到服务器,返回数据,表单提交
如果要查询部分数据,等于是将部分数据提交到服务器进行查询,得到数据返回from django.http import JsonResponsedef my_post_view(request):if request.method == 'POST':# 处理POST请求的逻辑post_data = request.POST# 进行相应的处理return JsonResponse({'message': 'Post请求已收到'})else:return JsonResponse({'error': '只允许POST请求'}, status=405)fetch('/post/', {method: 'POST',headers: {'Content-Type': 'application/json',// 其他头部信息...},body: JSON.stringify({ key1: 'value1', key2: 'value2' }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('请求出错:', error));import requestsurl = 'http://your-domain/post/'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.json())