【问题标题】:Sending one of multiple forms with jQuery使用 jQuery 发送多个表单之一
【发布时间】:2012-05-04 19:08:44
【问题描述】:

我正在做类似以下的事情:

$.each(data2, function(key2, val2) {
    $('#posts').append('<div class="send_comment" align="right">');
    $('#posts').append('<input type="hidden" class="com_post_id" value="'+i+'"><br /\>');
    $('#posts').append('Author: <input type="text" class="com_author"><br /\>');
    $('#posts').append('Img: <input type="text" class="com_img"><br /\>');
    $('#posts').append('Text: <input type="text" class="com_text"><br /\>');
    $('#posts').append('<button class="new_comment">Send</button>');
    $('#posts').append('</div>');
});

如何使用$.post 发送这些字段?使用$(this),我可以获得点击的元素,但是呢?

【问题讨论】:

  • 你需要在事件之后发送它吗,比如点击?你可以使用json来发送数据...

标签: javascript jquery forms click element


【解决方案1】:

由于它是动态注入元素,你应该使用jQuery on绑定功能

  $(function(){
      $(".send_comment").on("click",".new_comment",function(e){
         e.preventDefault();
         var item=$(this);
         var postId=item.parent().find(".com_post_id");   
         var author=item.parent().find(".com_author");  
         var msg=item.parent().find(".com_text");  

         $.post("yourPage.php", { id : postId, author:author ,msg:msg },function(result){
             //do whatever with result
              alert(result);
         });

      });
    });

http://api.jquery.com/on/

jQuery on 将适用于当前和未来的元素。

【讨论】:

  • @GiovanniCapuano:很高兴等你。
【解决方案2】:

data = $(this).closest('form').serialize()

【讨论】:

  • 确保字段具有name 属性,否则您将得到一个空值!
【解决方案3】:

我总是从 jqueryui 的网站上找到模态表单示例作为如何从表单发送数据的一个很好的例子:http://jqueryui.com/demos/dialog/#modal-form

基本上给你的字段ID,然后:

var author = $( "#author" ),
    image = $( "#image" ),
    text = $( "#text" ),
    allFields = $( [] ).add( author ).add( image ).add( text );

然后使用post:

$.post("your_url_that_processes_data",allFields, function(data){ 
   // do something with data 
});

如果您有多种形式略有不同,那么有很多方法可以解决这个问题。我建议要么更改操作 URL,要么以某种方式从某些 DOM 元素中获取“id”。也许您可以在脚本中将表单 id 更改为:"form-".id,然后在提交之前阅读它。

我可以尝试帮助更详细的用例吗?

【讨论】:

  • 我已经用 Shyju 的解决方案解决了,但也谢谢你的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多