简体   繁体   English

通过ajax提交具有多个字段的表单-如何将数据格式化为JSON?

[英]Submitting form with multiple fields via ajax - how to format the data into JSON?

I have a form with multiple data entries. 我有一个包含多个数据条目的表单。 Ajax (at the bottom) requires the data that is being passed to it to be bundled together. Ajax(在底部)要求将传递给它的数据捆绑在一起。 How do I take the un-submitted text in my form fields and bundle it into a JSON object to be sent to my Ajax? 我如何在表单字段中获取未提交的文本并将其捆绑到JSON对象中以发送到我的Ajax?

 <div id="editUserPinForm" class="ui raised segment signin">
  <div class="cmborder">
    <div class="form_heading">Edit Your Pin</div>
    <form>
      <div class="ui form attached fluid segment">
        <div class="two fields">
          <div class="field">
            <label>Title</label>
            <input type="text" name="pin[title]" class="ui input" value="{{pin/title}}">
          </div>
          <div class="field">
            <label>Activity</label>
            <input type="text" name="pin[activity]" class="ui input" value="{{pin/activity}}">
          </div>
        </div>
        <div class="field">
          <label>Description</label>
          <textarea name="pin[description]" class="ui input">{{pin/description}}</textarea>
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[guideID]" value="{{pin/guide_id}}">
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[lat]" value="{{pin/lat}}">
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[long]" value="{{pin/long}}">
        </div>
        <div class="inline field">
          <input type="submit" value="Submit Changes" class="ui blue submit button">
        </div>
      </div>
    </form>
  <span class='close_message' id="messageclose">&times;</span>
  </div>
</div>

<script>

  $( "#messageclose" ).on("click", function() {
      $('#editUserPinForm').fadeOut();
    });

  $("#editUserPinForm").submit(function() {
      $.ajax({
           type: "PATCH",
           url: "api/pins/{{pin/id}}",
           contentType: 'application/json',
           dataType: 'json',
           data: JSON.stringify( {pin:{description:value}})
           }).success: function(response){
               alert(response); //response from server.
           };
      });


</script>

I used jQuery Serialize instead and it worked like a charm. 我改用jQuery序列化,它像一个魅力。

https://github.com/macek/jquery-serialize-object https://github.com/macek/jquery-serialize-object

The problem with 问题所在

JSON.stringify($(this).serializeArray());

is that it converts an array into a JSON, but the array adds a "Name" and "Value" that makes the resultant JSON really hard to use. 是它将数组转换为JSON,但是数组添加了“名称”和“值”,这使得生成的JSON确实很难使用。

You could use the internal jQuery $('#domNode').serializeArray() which will return an array of all the inputs in an array of objects. 您可以使用内部jQuery $('#domNode')。serializeArray()来返回对象数组中所有输入的数组。 It follows the W3C pattern for returning the valid inputs for successful controls, meaning it will not return disabled controls. 它遵循W3C模式,用于为成功的控件返回有效的输入,这意味着它不会返回禁用的控件。

Ref: 参考:
https://api.jquery.com/serializeArray/ https://api.jquery.com/serializeArray/
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2 http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2

In order to send the form as a json string. 为了将表单作为json字符串发送。 You have to create an array with inputs names and values pairs, by gathering every input name and value to associate them in an array of objects containing the name and value pair : 您必须通过收集每个输入名称和值以将它们与包含名称和值对的对象数组相关联来创建具有输入名称和值对的数组:

$("#editUserPinForm").submit(function() {
jQuery("#editUserPinForm").find("input").each( function()
{

var form_data = new Array(); // The array that'll contain inputs names and values
form_data.push( { $(this).attr('name') : $(this).val() } );
var form_jsoned = JSON.stringify(form_data);

// Then here you can call ajax and send the json data
$.ajax({
       type: "PATCH",
       url: "api/pins/{{pin/id}}",
       contentType: 'application/json',
       dataType: 'json',
       data: form_jsoned
       }).success: function(response){
           alert(response); //response from server.
       };
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM