追加形式的价值

时间:2017-08-17 20:42:03

标签: javascript jquery forms

我正在尝试从表单中获取值并将其附加到表单,然后将该值作为参数传递

脚本

$(document).ready(function() {
$('#buttonClick').on('click', 'button',function firstCall(){

var form = new FormData();
form.append("name", "test");
form.append("phone", "2245201905");
form.append("url", "this_url");
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "url_path",
  "method": "POST",
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});});
});

HTML

<form method="post" id="formSample">
 <div class="form-group">
      <label for="name">Name</label>
      <input type="text" id="name" placeholder="Fullname">
 </div>
 <div class="form-group">
      <label for="phone">phone</label>
      <input type="number" name="phone" placeholder="number">
 </div>
 <div id="buttonClick">
 <button >Submit</button></div>

在我的脚本中,我已经硬编码了name,phone和url的值,它正在工作,因为我无法从表单中追加值。 所以我在寻找

form.append("name", "(document.getElementById('name').value");

同样在按钮上点击我无法传递数据,因为我已经发出警报但我没有我的代码输入功能

注意:我还没有处理过url部分

3 个答案:

答案 0 :(得分:2)

form.append("name", "(document.getElementById('name').value");

你在这里附加一个字符串。只需删除“

form.append("name", document.getElementById('name').value);

另外,您可能需要仔细查看javascript中的匿名functionsdata types

答案 1 :(得分:0)

要创建一个具有实际HTML值的FormData,您可以将该表单传递给表单数据作为参数

<form id="myForm">
   <input type="text" id="name" name="name" placeholder="Fullname">
   <input type="text" id="phone" name="phone" placeholder="Phone">
</form>
<script>
var myform = document.getElementById('myForm');
var form = new FormData(myform);
// form will have name and phone
form.append("url", window.location.href);

$.ajax(settings).done(function (response) {
   if (response.success) {
      // Only do something if the response data has success key.
   }
});});
</script>

答案 2 :(得分:0)

实际上,只需获取整个表单并将其传递给FormData constructor,您就可以更轻松地完成此操作。您应该为输入设置名称

&#13;
&#13;
echo
&#13;
function firstCall(e) {
      e.preventDefault();

      var htmlForm = document.getElementById('formSample');
      var form = new FormData(htmlForm);
      form.append("url", "this_url");
      
      // perform the ajax request
      form.forEach((e, i) => { console.log(i, e); });
}

$(document).ready(function() {
    // You can use named function if you need to reuse it elsewhere
    $('#buttonClick').on('click', 'button', firstCall);
});
&#13;
&#13;
&#13;