简体   繁体   English

什么是 ajax 的表格无效,我该如何渲染它?

[英]What is ajax gets invalid form, How can i render it?

I am working with Django and Ajax.我正在使用 Django 和 Ajax。 With the help of jQuery, i successfully sent form data to server and able to validate it.在 jQuery 的帮助下,我成功地将表单数据发送到服务器并能够对其进行验证。

Problem arrive when form is invalid, i want that, if the form is invalid, ajax get the invalid form and render it to same template with errors like all invalid forms do.当表单无效时问题出现,我希望,如果表单无效,ajax 会获取无效表单并将其呈现到相同的模板,并出现错误,就像所有无效的 forms 一样。

How Can i do it?我该怎么做?

The closest method you can do is to return Form.errors .您可以做的最接近的方法是返回Form.errors For example:例如:

def submitSample(request):
    form = SampleForm(request.POST)
    response_data = {}

    if form.is_valid():
        form.save()
        response_data['result'] = 1
    else:
        response_data['result'] = 0
        response_data['errors'] = form.errors

    return HttpResponse(response_data)

The response_data['errors'] will contain a dictionary of error messages like: response_data['errors']将包含错误消息字典,例如:

{'title':['This field is required.']}

After sending the ajax request, you can use jQuery to display the errors on the form elements.发送 ajax 请求后,您可以使用 jQuery 在表单元素上显示错误。 Note that you will have to find a way to append the error messages next to their elements.请注意,您将必须找到一种方法来 append 其元素旁边的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 ajax function 中呈现 Django render() 响应? - How can I render a Django render() response in an ajax function? 如何使用 vuetify 呈现 Django 表单? - How can I render Django Form with vuetify? 如何跳过模板并使用Ajax将请求数据呈现给它? - How can I skip to a template and render the request data to it using ajax? Django Bootstrap表单呈现缓慢,如何加快速度? - Django Bootstrap form is slow to render, how can I speed up? 渲染模板后如何重置表单并隐藏模式 - How can I reset form after render template and hide modal 如果登录无效,如何将 email 再次返回到表单 - How I can return the email again to the form if the login is invalid 如何在 Django 中创建这样的表单,这种表单的名称是什么? - How can I create such a form in Django and what is the name of this type of form? 我的Django模型表格没有保存,因为它无效,但我看不出有什么问题 - My Model form for Django is not saving because it's invalid but I can't see what's wrong Django和Ajax:如何实现带有建议的表单文本输入? - Django and Ajax: how can I implement a form text input with suggestions? 如何使用Ajax处理render_to_response,以便可以使用内容重定向页面? - How can i handle render_to_response with ajax, so that the page could be redirected with the content?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM