【问题标题】:django get data from api with ajaxdjango 使用 ajax 从 api 获取数据
【发布时间】:2019-10-18 11:49:04
【问题描述】:

我试图从 使用 ajax 的 API 获取一些信息。我能够发布数据,但我无法从服务器获取所有数据。我是 Django 环境中的新手,虽然我尝试了一些参考资料。 我想使用我提供的 API 从服务器获取数据,并使用 ajax get 调用显示这些数据。

我遵循的参考:

1.Django Ajax Jquery Call

2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html

3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html

我的 get 调用代码:

         $.ajax({
            type: "GET",
            url: "/save_composition",
            dataType: "json",
            success: function(data) {
                alert(data)
            },
            error: function(xhr, textStatus) {
                   alert("error..");
            }});

网址部分:

path('restore_composition/', views.restore_composition, name='restore_composition')

Views.py:

def restore_composition(request):
   data = SaveComposition.objects.all()
   return render(request, 'index.html', context={'data': data})

【问题讨论】:

  • 你在哪里定义了你的save_compositionmethod/url?
  • 我在某些时候误解了。端点是问题。感谢您的合作。

标签: python jquery django ajax


【解决方案1】:

这就是 ajax 调用在 Django 框架中的工作方式。

def ajax_method():
    return HttpResponse(200)

ajax 调用的网址

path('save_composition', views.ajax_method, name='ajax_method')

你需要设置不带正斜杠的`url-path'

Ajax 调用

$.ajax({
        type: "GET",
        url: "save_composition",
        dataType: "json",
        success: function(data) {
            alert(data)
        },
        error: function(xhr, textStatus) {
               alert("error..");
        }});

【讨论】:

  • 好吧,看来方法对了,我已经提到我是 Django 和 ajax 环境的新手,所以感谢您的合作。
猜你喜欢
  • 1970-01-01
  • 2018-05-11
  • 2020-09-23
  • 2018-10-06
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2012-03-16
相关资源
最近更新 更多