尝试向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模式是在&#34; 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)
最后,home.html来自ajax请求:
<!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>
答案 0 :(得分:2)
删除网址正则表达式$
之前的尾部斜杠或在$之前使用?
。
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^chart_data$', views.chart_data, name='chart_data')
]
您也可以在模板中按名称引用{% url 'app:url_name' %}
您还需要传递csrf令牌和帖子数据。
{% csrf_token %}
<script>
var timeArray = [0,10,20,30,40,50,60];
var dataArray = [0,0,0,0,0,0,0];
$.ajax({
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
url: {% url 'headstation:chart_data' %},
type:"POST",
data: {
'data': 'temperature',
'csrfmiddlewaretoken': csrftoken,
},
dataType: 'json',
success: function (data) {
if (data) {
timeArray = data.x;
dataArray = data.y;
alert("recieved");
}
}
});
</script>
答案 1 :(得分:0)
您可以使用''(空格)代替^$
。它对我有用。
url('^$', views.index, name='index'),
url('about/', views.about, name='about'),