从 AJAX 函数调用 Django 视图

Calling Django view from AJAX function

我有一个传递对象 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视图,但没有显示视图。按钮应呈现相应的页面。

代码一切正常,但正如 中突出显示的那样,我们只需要给 windows.location 一个从 AJAX 中定义的变量。甜的 !