【问题标题】:Javascript Submitting Data to Form TwiceJavascript 向表单提交数据两次
【发布时间】:2012-10-29 13:00:01
【问题描述】:

假设我有一个简单的表格:

​<form id="new_stuff">
    <label>Title </label>
        <input id="title" maxlength="255" name="new[title]" size="50" type="text"><br /><br />
    <label>Message </label>
        <input id="message"  name="new[message]" size="50" type="text" value="general"><br />
    <label>Upload </label>
        <input id="upload_data" name="new[upload]" size="30" type="file"><br />
    <input id="submitform" action="form.php" type="button" value="submit me" formmethod="post"/>
​</form>

当用户填写数据并点击提交时,我需要一种方法来获取数据,更改标题(假设在用户输入的任何内容的末尾添加单词“TESTING”)然后提交表单两次;一次使用原始数据,另一次使用更改后的数据。

任何人都可以帮助我在 JS 中执行此操作的方法。谢谢

【问题讨论】:

  • 这最好在服务器端处理。即发布一次表格,处理两次。
  • 您应该在服务器端执行此操作,因为它更安全、更轻松、更好。
  • +1 在服务器端处理它,否则请查看onsubmit 事件
  • 我无法访问服务器端,所以需要在客户端完成。

标签: javascript forms double-submit-problem


【解决方案1】:

一点点 jQuery 让这很容易。

$( "#new_stuff" ).submit( function () {
  var self = this;
  // Save the form data as-is, before making any changes
  var originalFormData = $( self ).serialize();

  // Make changes to the values that you want to change.
  $( "#title" ).val( $( "#title" ).val() + ' TESTING' );

  // Serialize the form a second time
  var modifiedFormData = $( self ).serialize();

  // Post the form to your location.
  $.post('url', originalFormData);
  $.post('url', modifiedFormData);

  // Return false, otherwise the form action will post (a third time).
  return false;
});

【讨论】:

  • OP 没有提到他想要 jQuery。
  • 他没有说他不想要 jQuery。
  • jQuery 可能是一个选项,但据我所知,我认为 serialize() 不支持表单具有的文件元素。
猜你喜欢
  • 2011-06-17
  • 2016-04-22
  • 1970-01-01
  • 2013-03-27
  • 2014-11-03
  • 2015-04-04
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多