本文介绍了通过具有相同名称的多个输入通过ajax发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery完成以下任务.

I am attempting to accomplish the following using jQuery.

我有7个输入,一周中每天有1个输入.用于此的html是在服务器端生成的.对于每一天,我都有一个文本输入和一个链接,用于仅通过ajax将当天的文本提交到服务器.

I have 7 inputs, one for each day in the week. The html for this is generated server side.For each day I have a text input and a link for submitting the text for that day only via ajax to the server.

到目前为止,我已经拥有

So far I have

<script type="text/javascript">
    $().ready(function(){
       $('.add_dish').click(function(){
          var mydata = $('form input[name=user_input]').val();
          window.alert(mydata)

          $.ajax({
            type: 'POST',
            url: '/add',
            data: mydata,
            cache: false,
            success: function(result) {
              if(result == "true"){
              }else{
              }
            }
          });
       });
    });
</script>

服务器端生成的代码:

<h1>First day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

<h1>Second day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

<h1>Third day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

当我单击Add 时,总是显示第一天输入的值.

When I click Add the value of the the input of the first day is always displayed. How can it be changed to reflect the selections of the element in the same <form> as the submitting link is in?

编辑:
突出显示了问题的第二部分.

EDIT:
Highlighted the second part of the question.

推荐答案

您使用jQuery选择器的方式错误.

you are using jQuery selector the wrong way.

应该是这样的:

 var mydata = $('form input[name=user_input]').attr('value','something');

,如果您只是想将输入框的值放在mydata中:

and if you just want the value of the input box to put in mydata :

var mydata = $('form input[name=user_input]').val();

要迭代具有相同名称的所有输入,必须使用.each():

For iterating on all the inputs with same name you have to use .each():

    $('.add_dish').click(function(){

              $('form input[name=user_input]').each(function(){
              var mydata = $(this).val();
              window.alert(mydata);
              });


              $.ajax({
                type: 'POST',
                url: '/add',
                data: mydata,
                cache: false,
                success: function(result) {
                  if(result == "true"){
                  }else{
                  }
                }
              });
           });

参考文献:

jQuery输入选择器

jQuery类选择器

jQuery .each()

这篇关于通过具有相同名称的多个输入通过ajax发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:11