Django 基于jquery的ajax实现post请求
- Django url.py
from django.contrib import admin
from django.urls import path
from apps.message import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index,name="index"),
path('index/ajax/', views.index_ajax, name="index_ajax"),
]
- Django views,py
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def index(request):
if request.method == "POST":
print("post")
return render(request, 'index.html',)
@csrf_exempt
def index_ajax(request):
if request.method == "POST":
print("post",request.POST.get("username"),request.POST.get("password"))
data = {'code': 200, 'msg': 'OK'}
return HttpResponse(json.dumps(data))
- index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
</head>
<body>
<script>
var data = {
"name": "test",
"age": 1
}
$.ajax({
async:false, //是否异步
url: "ajax/", //留空白发送给自己,开头不加/ 发送给/index/...
type: "POST", //请求类型
data: { //发送数据 键值对形式
username: "Q1mi",
password: 123456
},
success: function (data) {
alert(data) //回调函数
}
})
</script>
</body>
</html>
ajax轮询
<script>
setInterval(function () {
//ajax轮询获取
$.ajax({
type:"POST",
url:"/index/static_submit_f1_ajax/",
data:{},
success:function(data){
$(').val(data["file_new"])
$(').val(data["file_len"])
},
});}, 500);
</script>