【问题标题】:Django; error on printing JSON response in Firefox console姜戈;在 Firefox 控制台中打印 JSON 响应时出错
【发布时间】: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


【解决方案1】:

把 urls.py 改成这样:

from .views import get_data

app_name = 'javascript'
urlpatterns = [
    path('', views.index, name='index'),
    path('api/data[/]?$', get_data, name='api-data'),

]

您的 AJAX 调用是对 'api/data/' 的,它与您的 path('api/data', get_data, name='api-data') 不匹配。现在有了'api/data[/]?$',它将匹配或不匹配最后一个/

【讨论】:

  • 我的荣幸 ;-)
猜你喜欢
  • 2017-03-19
  • 2021-12-09
  • 1970-01-01
  • 2014-05-09
  • 2018-09-08
  • 2021-02-09
  • 2017-11-05
  • 2017-10-06
  • 2015-04-07
相关资源
最近更新 更多