【问题标题】:Render form in View and attach additional data as json在视图中呈现表单并将附加数据附加为 json
【发布时间】:2016-07-31 10:24:26
【问题描述】:

我有一个模态,我在其中呈现一个表单。在它打开它从 View 函数请求内容之前。现在我想传递我可以在 ajax.success: 函数中处理的其他属性。

阿贾克斯:

function task_form() {
$.ajax({
    url : "/somewhere/" , // the endpoint
    type : "GET", // http method

    // handle a successful response
    success : function(data) {
    if(data.attr == "whatever"){ 
      do this
    }else{
      do that
    }},

    // handle a non-successful response
    error : function(xhr,errmsg,err) {
                errorstuff
    }
});
};

查看:

def someview(request):
if request.method == 'POST':
    print("shouldnt happen")
else:
    form = SomeForm()
    response_data = {'form': form}

return render(request, 'formToInsert.html', response_data)

我尝试使用 JsonResponse() 但我不确定如何将 html 放入 dict 中以及如何在 js 端使用它。

【问题讨论】:

    标签: jquery json ajax django django-views


    【解决方案1】:

    你的视图应该这样做:

    def someview(request):
    if request.method == 'POST':
        print("shouldnt happen")
    else:
        form = SomeForm()
        response_data = {'form': form}
    
    return HttpResponse(json.dumps(response_data), content-type="application/json")
    

    虽然我不确定 SomeForm() 是否可以通过“json”包进行序列化。否则你可能会使用 Django 'serialize' 包来做同样的事情。

    【讨论】:

    • 序列化基本上是我的问题。这样做的最佳方法是什么?您如何将响应“反序列化”为 ajax.success 中的 html?还是有一种我看不到的超级简单的方法? :D
    • 你需要展示一些你尝试过的代码。你试过我的回答吗?在 Javascript 中,您将设置 dataType: 'json',然后您应该能够像使用任何其他 json 对象一样使用返回的数据
    猜你喜欢
    • 2020-07-28
    • 2017-08-23
    • 2016-04-27
    • 1970-01-01
    • 2014-04-09
    • 2011-02-11
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多