【问题标题】:how to pass primary key value from JsonResponse to dynamic url in Django?如何将主键值从 JsonResponse 传递到 Django 中的动态 url?
【发布时间】:2019-03-10 15:20:46
【问题描述】:

我遇到了在 Django 中使用 Ajax 将主键值传递给动态 url 的问题。感谢您的帮助...

下面是点击按钮功能的JS代码:

$(function () {

  $(".js-create-book").click(function () {
      $.ajax({
      url: '/supplier/**<int:pk>**/new/',
      type: 'get',
      dataType: 'json',
      beforeSend: function () {
        $("#modal-book").modal("show");
      },
      success: function (data) {
        $("#modal-book .modal-content").html(data.html_form);
      }
    });
  });

});

views.py 得到的函数 new_stok() 如下:

def new_stok(request, pk):
    supplier = get_object_or_404(Supplier, pk=pk)
    form = NewStokForm()
    context = {'pk': supplier.pk, 'form': form}
    html_form = render_to_string('includes/partial_stok_create.html',
        context,
        request=request,
    )
    return JsonResponse({'html_form': html_form})

【问题讨论】:

  • id 是从哪里来的?

标签: json ajax django


【解决方案1】:

您可以使用 HTML5 数据属性:

<button class="js-create-book" data-id="{{ supplier.pk }}">Add new</button>

然后在javascript中检索属性:

$(function () {

   $(".js-create-book").click(function () {
      var data_id = $(this).attr("data-id");
      $.ajax({
      url: '/supplier/' + data_id + '/new/',
      type: 'get',
      dataType: 'json',
      beforeSend: function () {
        $("#modal-book").modal("show");
      },
      success: function (data) {
        $("#modal-book .modal-content").html(data.html_form);
      }
    });
  });

});

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    相关资源
    最近更新 更多