jQuery Ajax表单数组提交 [英] Jquery ajax form array submit

查看:268
本文介绍了jQuery Ajax表单数组提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单评论部分,用户可以在其中回复评论.每个评论都有一个带有回复框的表单.我正在从数据库中获取注释并运行以下循环.

I have a form comment section whereby a user can reply to a comment. Each comment has a form with a reply box. Am getting the comments from the database and running the following loop.

@foreach($responses as $response)

<li>{{$response->answer}}</li>

<form action="{{action('DiscussionController@postAnswerQuestion', [$entry_year, $grade_id, $subject_id, $question_id])}}" method="post" id="form1">
<input type="text" name="reply" value="" placeholder="Reply">
<input type="hidden" name="response_id" value="{{$response->id}}">
<input type="submit" name="" value="reply">
 </form>
  @endforeach

当我使用普通的PHP提交php表单时,它提交的很好,但是当使用jquery ajax和以下代码时.

When I submit the php form using normal PHP it submits just fine but when using jquery ajax and the following code.

  var formData = {
        'answer'            : $('input[name=answer]').val(),
        'reply'             : $('input[name=reply]').val(),
        'response_id'       : $('input[name=response_id]').val(),
    };

仅在进行一些谷歌搜索之后,它才返回第一个输入的值,我发现我应该使用序列化,因此我使用以下

It returns the value of the first input only after some googling I found that I should use serialize and so instead of the above jquery code I used the following

        var formData = $('#form1').serialize();

但是现在值arent被捕获,并且这些值以空值形式出现在php中.我该如何解决以上问题?

But now the values arent being captured and the values are coming to php as null. How should I solve the above problem?

非常感谢你们!

推荐答案

首先,将表单上的id替换为class.

First, replace the id on the form with a class.

<form action="..." method="post" class="commentForm">
<input type="text" name="reply" value="" placeholder="Reply">
<input type="hidden" name="response_id" value="{{$response->id}}">
<input type="submit" name="" value="reply">
</form>

然后在表单上注册一个提交事件处理程序以进行ajax调用.在事件处理程序回调中,this表示正在提交的表单.您可以使用它来获取该表单的输入值.

Then register a submit-event handler on the forms to make the ajax call. Inside the event handler callback, this refers to the form being submitted. You can use that to get the values of the inputs for that form.

$('.commentForm').submit(function(event) {
    event.preventDefault();

    var $form = $(this);
    var formData = {
        answer     : $form.find('input[name=answer]').val(),
        reply      : $form.find('input[name=reply]').val(),
        response_id: $form.find('input[name=response_id]').val()
    };

    // Make the ajax call here.
});

但是,您应该可以跳过将formData对象放在一起,并在ajax调用中使用以下内容:

However, you should be able to skip putting together the formData object, and use the following for your ajax call:

data: $(form).serialize(),

这篇关于jQuery Ajax表单数组提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆