【问题标题】:Calling Django view from AJAX function从 AJAX 函数调用 Django 视图
【发布时间】:2019-01-20 11:11:12
【问题描述】:

我有一个传递对象 ID 的按钮。按下按钮时,我希望显示其相应的 Django 视图。

views.py

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def updateUser(request, id):

    user= get_object_or_404(CustomUser, pk=id)
    if request.method == 'POST':
        form = UpdateUser(request.POST, instance=user)
        try:
            print("DJANGO VIEW")
            if form.is_valid():
                form.save()
                messages.success(request, ("New user account has been created"))
            else:
                messages.warning(request, ("Data in fields is incorrect, please try again"))
        except Exception as e:
            messages.warning(request, ("Error: {}". format(e)))
    else:
        form = UpdateUser(instance=user)
    context ={'form': form, 'user': user,}
    return render(request, 'user/updateUser.html', context)

urls.py

 path('updateUser/<int:id>/', views.updateUser, name="updateUser"),

my.js

function myfunction($this) {

    var stid = $this;
   console.log("button clicked");
    var request_data = '/user/updateUser/'+stid;
    alert(request_data);
    console.log("data: " + stid);
    $.ajax({
        url:  "../updateUser/" + stid+"/" ,
        contentType: "application/json; charset=utf-8",
        processData: true,
        type:  'post',
        dataType:  'html',

        success:  function (data) {
           alert("Success");
           $("#updateUser").html(response);
        },
         error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + ':' + errorThrown);
         }
    });
}

Django 视图被调用,但视图不显示。按钮应呈现相应的页面。

【问题讨论】:

  • “调用 Django 视图”是指看到“成功”警报吗?如果发生这种情况但文档没有更改,请检查您的 html(您没有在此处提供)-您确定有一个 id 为 updateUser 的元素吗?
  • 我只想显示页面“updateUser/1/”。
  • 我有点困惑。如果您只想让按钮转到新页面,那么只需使用链接。您的脚本会将新页面的内容放入现有页面的元素中,而无需重新加载页面。这有什么不好的?如果它根本不起作用,那么您是否按照我的建议检查了您的 html?

标签: javascript ajax django django-2.1


【解决方案1】:

代码一切正常,但正如link 中强调的那样,我们只需要给 windows.location 一个由 AJAX 定义的变量。甜的 !

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 2020-08-31
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2014-08-18
    • 2021-10-21
    • 2023-03-25
    • 2015-03-06
    相关资源
    最近更新 更多