English 中文(简体)
How to thePOST a django form with AJAX & jQuery
原标题:How to POST a django form with AJAX & jQuery

我抽查了几吨推土器,但其中每一个都告诉你这样做的一种方式,其中没有一个是简单的,而我是混淆不清的,因为我从未与阿富汗复兴共和军合作。

I have a model called "note", a modelform for it, and inside the template I need that everytime a note element sends the stop() signal (from jQuery Sortables) django updates the object.

我目前的法典:

<>views.py

def save_note(request, space_name):

    """
    Saves the note content and position within the table.
    """
    place = get_object_or_404(Space, url=space_name)
    note_form = NoteForm(request.POST or None)

    if request.method == "POST" and request.is_ajax:
        msg = "The operation has been received correctly."          
        print request.POST

    else:
        msg = "GET petitions are not allowed for this view."

    return HttpResponse(msg)

JavaScript:

function saveNote(noteObj) {
    /*
        saveNote(noteObj) - Saves the notes making an AJAX call to django. This
        function is meant to be used with a Sortable  stop  event.
        Arguments: noteObj, note object.
    */
    var noteID = noteObj.attr( id );

    $.post("../save_note/", {
        noteid: noteID,
        phase: "Example phase",
        parent: $( #  + noteID).parent( td ).attr( id ),
        title: $( #  + noteID +   textarea ).val(),
        message: "Blablbla",
    });
}

现行代码从模板中获取数据,并在终端中打印。 我不知道我如何操纵这一数据。 我看到一些人通过分类管理数据,将数据发送到 d。

我如何能够查阅美国宇宙航空研究开发机构提供的数据,并更新说明标的?

最佳回答

Since you are using jQuery why not use the following:

<script language="JavaScript">
    $(document).ready(function() {
        $( #YOUR_FORM ).submit(function() { // catch the form s submit event
            $.ajax({ // create an AJAX call...
                data: $(this).serialize(), // get the form data
                type: $(this).attr( method ), // GET or POST
                url: $(this).attr( action ), // the file to call
                success: function(response) { // on success..
                    $( #DIV_CONTAINING_FORM ).html(response); // update the DIV 
                }
            });
            return false;
        });
    });
</script>

http://www.ohchr.org。

正如在评论中指出的,上述工作有时取得了一些成绩。 因此:

<script type="text/javascript">
    var frm = $( #FORM-ID );
    frm.submit(function () {
        $.ajax({
            type: frm.attr( method ),
            url: frm.attr( action ),
            data: frm.serialize(),
            success: function (data) {
                $("#SOME-DIV").html(data);
            },
            error: function(data) {
                $("#MESSAGE-DIV").html("Something went wrong!");
            }
        });
        return false;
    });
</script>
问题回答

如果是:

request.POST["noteid"]
request.POST["phase"]
request.POST["parent"]
... etc

请求。 POST物体不可变。 你们应当把价值分配给一个变量,然后加以操纵。

我建议你使用,以便你能够书写正常的超文本形式,然后将其“升级”带给美国航天中心。 在你们的法典中,在任何地方都有一笔钱。

此外,利用该网络对“火焰”或“谷歌”的开发工具的看法,你可以看看你AJAX电话发出什么。

想看一下的是,在将表格退回时,表格被装成一种模式。

View.py

@require_http_methods(["POST"])
def login(request):
form = BasicLogInForm(request.POST)
    if form.is_valid():
        print "ITS VALID GO SOMEWHERE"
        pass

    return render(request,  assess-beta/login-beta.html , { loginform :form})

1. 简单地看待归还html

www.un.org/Depts/DGACM/index_spanish.htm 表格html

<form class="login-form" action="/login_ajx" method="Post"> 
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="header">Authenticate</h4>
  </div>
  <div class="modal-body">
        {%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
        <div class="fieldWrapper form-group  has-feedback">
            <label class="control-label" for="id_email">Email</label>
            <input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
            {%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
        </div>
        <div class="fieldWrapper form-group  has-feedback">
            <label class="control-label" for="id_password">Password</label>
            <input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
            {%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
        </div>
  </div>
  <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
</div>
</form>

Page containing the modal

<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog">{% include "assess-beta/login-beta.html" %}</div>

Use the include tag to load the snipped on page load so it is available when you open the modal.

<>Modal.js

$(document).on( submit ,  .login-form , function(){
$.ajax({ 
    type: $(this).attr( method ), 
    url: this.action, 
    data: $(this).serialize(),
    context: this,
    success: function(data, status) {
        $( #LoginModal ).html(data);
    }
    });
    return false;
});

在本案中使用(on)这一条,关键在于使提交活动对纽伦而不是对文件具有约束力。

由于其他答复确实奏效,我倾向于使用。 j Query Form Plugin。 它完全支持你们所希望和更多的东西。 员额观点按惯例在Django部分处理,只是退回正在替换的超文本。

On the server side, your django code can process the AJAX post the same way it processes other form submissions. For example,

views.py

def save_note(request, space_name):

    """
    Saves the note content and position within the table.
    """
    place = get_object_or_404(Space, url=space_name)
    note_form = NoteForm(request.POST or None)

    if request.method == "POST" and request.is_ajax():        
        print request.POST
        if note_form.is_valid():
            note_form.save()
            msg="AJAX submission saved"
        else:
            msg="AJAX post invalid"
    else:
        msg = "GET petitions are not allowed for this view."

    return HttpResponse(msg)

I ve assumed your NoteForm is a ModelForm -- which it should be -- so it has a save method. Note that in addition to adding the save() command, I changed your request.is_ajax to request.is_ajax(), which is what you want (if you use request.is_ajax your code will just check whether the request has a method called is_ajax, which obviously it does).

大部分使用AJAX POST和Django表格的例子,包括官方例子:

https://docs.djangoproject.com/en/1topics/class-based-views/generic-editing/#ajax-example

are fine when ModelForm.clean() did not produce any errors (form_valid). However, they do not perform hard part: translating ModelForm errors via AJAX response to Javascript / DOM client-side.

我的简略应用利用AJAX应急反应,与客户和亲眼镜一起,自动显示AJAX员额的班级观点:ModelForm 验证错误,类似于将如何在传统的HTTP POST中展示这些错误:

https://django-jinja-knockout.readthedocs.org/en/latest/forms.html#ajax-forms-processing https://django-jinja-knockout.readthedocs.org/en/latest/viewmodels.html

Jinja2和Django模板发动机都得到了支持。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签