【发布时间】:2018-03-28 08:30:12
【问题描述】:
尝试向 django 服务器发送 ajax 请求并获得包含一些随机数据的响应。
首页正常,但是ajax请求报404错误如下:
Using the URLconf defined in bms_project.urls,
Django tried these URL patterns, in this order:
^headstation/
^admin/
The current path, chart_data/, didn't match any of these.
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
url 模式是在“headstation”目录中的 urls.py 文件中侦听,然后包含在普通 urls.py 脚本中。它适用于主页:
项目 urls.py
urlpatterns = [
url(r'^headstation/', include('headstation.urls')),
url(r'^admin/', admin.site.urls),
]
headstation urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^chart_data/$', views.chart_data, name='chart_data')
]
views.py
def index(request):
# get context of request from client
context = RequestContext(request)
# construct dictionary to pass template + context
context_dict = {'buildingName': 'The Building',
'boldmessage': 'Put a message here'}
#render and return to client
return render_to_response('headstation/home.html', context_dict, context)
def chart_data(request):
if (request.method == 'POST'):
dataX = [0,10,20,30,40,50,60]
dataY = [25.0,24.2,25,24.0,24.5,25.1,25.5]
response = {"x": dataX,
"y": dataY}
return JsonResponse(response)
最后是 ajax 请求来自的 home.html:
<!DOCTYPE html>
<head>
<title>Homepage</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<h1>{{ buildingName }}</h1>
Hello, message: <strong>{{ boldmessage }}</strong><br />
<a href="/another-page/">Link to another page</a><br />
<h1>Chart</h1>
<script>
var timeArray = [0,10,20,30,40,50,60];
var dataArray = [0,0,0,0,0,0,0];
$.ajax({
url: '/chart_data/',
type:"POST",
data: {
'data': 'temperature'
},
dataType: 'json',
success: function (data) {
if (data) {
timeArray = data.x;
dataArray = data.y;
alert("recieved");
}
}
});
</script>
</body>
【问题讨论】:
-
我认为网址应该是
url: 'headstation/chart_data/', -
刚刚尝试过 - 当前路径
headstation/headstation/chart_data/与其中任何一个都不匹配。同样的错误! -
你试过
chart_data/没有前导/吗? -
是的,也没有运气......
-
@csrf_exempt 并且已修复
标签: javascript jquery python ajax django