8.ajax与django后台json数据的交互

时间:2023-03-10 02:29:25
8.ajax与django后台json数据的交互

1新建django项目名为json_ajax,应用名为app,在templates模板中新建ajax.html文件

ajax.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
{% load staticfiles %}
<script type="text/javascript" src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
</head>
<body>
<button id="send">发送</button>
<script>
$("#send").click(function () {
{#json数据#}
var post_data={
"name":"weihu",
}; $.ajax({
url:"http://127.0.0.1:8000/ajax",
type:"POST",
{#发送json数据到服务器#}
data:post_data, {#请求成功回调函数#}
success:function (data) {
alert(data)
alert("请求成功")
},
{#请求失败回调函数#}
error:function () {
alert("服务器请求超时,请重试!")
} });
});
</script>
</body>
</html>

 

2.在settings配置文件中,注释

 # 'django.middleware.csrf.CsrfViewMiddleware',
STATIC_URL = '/static/'

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

3.在urls.py文件中,配置path路径

"""json_ajax URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
. Add an import: from my_app import views
. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
. Add an import: from other_app.views import Home
. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
. Import the include() function: from django.urls import include, path
. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app import views urlpatterns = [
path('admin/', admin.site.urls),
path('test',views.test),
path('ajax',views.ajax),
]

4.在views.py中,实现逻辑代码

from django.shortcuts import render,HttpResponse
import json def test(request):
return render(request,'ajax.html') def ajax(request):
if request.method=="POST":
name=request.POST.get('name')
print("ok")
status=
result="sucuss"
return HttpResponse(json.dumps({
"status":status,
"result":result,
"name":name
}))