Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery将表单数据转换为JavaScript对象(Convert form data to JavaScript object with jQuery)

How do I convert all elements of my form to a JavaScript object?

(如何将表单的所有元素转换为JavaScript对象?)

I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element.

(我希望有一些方法可以自动从表单中构建JavaScript对象,而不必遍历每个元素。)

I do not want a string, as returned by $('#formid').serialize();

(我不需要$('#formid').serialize();返回的字符串$('#formid').serialize();)

, nor do I want the map returned by $('#formid').serializeArray();

(,也不希望$('#formid').serializeArray();返回的地图)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

serializeArray already does exactly that.

(serializeArray已经做到了。)

You just need to massage the data into your required format:

(您只需要将数据整理成所需的格式:)

function objectifyForm(formArray) {//serialize data function

  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }
  return returnArray;
}

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.

(注意与真实输入同名的隐藏字段,因为它们会被覆盖。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...