【发布时间】:2018-03-16 15:11:02
【问题描述】:
网址.py:
from .views import get_data
app_name = 'javascript'
urlpatterns = [
path('', views.index, name='index'),
path('api/data', get_data, name='api-data'),
]
Views.py:
from django.http import JsonResponse
def get_data(request):
dictionary = {'Name':'John'}
return JsonResponse(dictionary)
def index(request):
return render(request, 'javascript/index.html')
索引.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
method: "GET",
url: "/api/data/",
success: function(dictionary){
console.log(dictionary)
},
error: function(error_data){
console.log("errorrr")
console.log(error_data)
}
})
</script>
使用 AJAX,我想在 index.html 加载时打印字典内容。但是,由于某种原因,Ajax 调用失败。 Console.log 输出为:
errorrr
127.0.0.1:8000:30:3
Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }
我的 jQuery 写法有什么错误吗?
【问题讨论】:
-
你得到'errorrr',因为你告诉它用这行
console.log("errorrr")打印它。 ajax 调用由于某种原因失败,因此它执行错误函数中的代码,该函数将字符串“errorrr”和错误数据打印到控制台(这是您在代码中使用这些行指定的内容:error: function(error_data){ console.log("errorrr") console.log(error_data) })跨度> -
谢谢亚当,我明白了。我更想知道为什么通话失败:)
-
没错,这可能会更有用。 ajax调用返回什么错误码?
-
在 ajax 请求中你调用
url: "/api/data/"但是匹配正则表达式的 url 没有最后一个/试试这个:path('api/data/', get_data, name='api-data'),
标签: python jquery json ajax django