양식 데이터를 JSON으로 직렬화 [중복]
이 질문에는 이미 답변이 있습니다.
Backbone.js 모델 에서 양식의 서버 사전 유효성 검사를 수행하고 싶습니다 . 이렇게하려면 양식의 사용자 입력을 사용 가능한 데이터로 가져와야합니다. 이것을 수행하는 세 가지 방법을 찾았습니다.
var input = $("#inputId").val();
var input = $("form.login").serialize();
var input = $("form.login").serializeArray();
불행히도, 그중 어느 것도 필자가 필요로하는 훌륭한 reabable 및 개발 가능한 JSON 객체를 제공하지 않습니다. 이미 Stack Overflow에 대한 몇 가지 질문을 살펴 보았지만 추가 라이브러리 만 발견했습니다.
하지 않습니다 Underscore.js , 현재 jQuery를 또는 Backbone.js는 도우미 방법을 제공?
그런 기능에 대한 요청이 없다고 상상할 수 없습니다.
HTML
<form class="login">
<label for="_user_name">username:</label>
<input type="text" id="_user_name" name="user[name]" value="dev.pus" />
<label for="_user_pass">password:</label>
<input type="password" id="_user_pass" name="user[pass]" value="1234" />
<button type="submit">login</button>
</form>
자바 스크립트
var formData = $("form.login").serializeObject();
console.log(formData);
출력
{
"name": "dev.pus",
"pass": "1234"
}
Backbone.js 모델
var user = new User(formData);
user.save();
이 사용 사례에 대한 기능은 다음과 같습니다.
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
용법:
var $form = $("#form_data");
var data = getFormData($form);
당신은 이것을 할 수 있습니다 :
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() ); // <-----------
console.log( data );
return false; //don't submit
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<button type='submit'>Try</button>
</form>
이것을보십시오 : http://www.json.org/js.html
아래 코드가 도움이 될 것입니다. :)
//The function is based on http://css-tricks.com/snippets/jquery/serialize-form-to-json/
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form.login').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeObject();
console.log(formData);
$('.datahere').html(formData);
});
});
</script>
사용하다:
var config = {};
jQuery(form).serializeArray().map(function(item) {
if ( config[item.name] ) {
if ( typeof(config[item.name]) === "string" ) {
config[item.name] = [config[item.name]];
}
config[item.name].push(item.value);
} else {
config[item.name] = item.value;
}
});
나는 이것이 도우미 함수 요구 사항을 충족시키지 못한다는 것을 알고 있지만, 내가 한 방법은 jQuery의 $ .each () 메소드를 사용하는 것입니다.
var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
function(i, v) {
loginFormObject[v.name] = v.value;
});
그런 다음 loginFormObject를 백엔드에 전달하거나 userobject를 작성하고이를 백본에도 저장할 수 있습니다.
이 문제를 해결할 답변을 찾을 수 없습니다.
[{name:"Vehicle.Make", value: "Honda"}, {name:"Vehicle.VIN", value: "123"}]
이것은이 객체를 요구합니다 :
{Vehicle: {Make: "Honda", "VIN": "123"}}
그래서이 문제를 해결할 직렬 변환기를 작성해야했습니다.
function(formArray){
var obj = {};
$.each(formArray, function(i, pair){
var cObj = obj, pObj, cpName;
$.each(pair.name.split("."), function(i, pName){
pObj = cObj;
cpName = pName;
cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
});
pObj[cpName] = pair.value;
});
return obj;
}
아마 누군가를 도울 것입니다.
동일한 이름의 반복 양식 요소에 신경 쓰지 않으면 다음을 수행 할 수 있습니다.
var data = $("form.login").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));
Underscore.js를 여기에서 사용하고 있습니다.
Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.
This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.
If you are sending the form with JSON you must remove [] in the sending string. You can do that with the jQuery function serializeObject():
var frm = $(document.myform);
var data = JSON.stringify(frm.serializeObject());
$.fn.serializeObject = function() {
var o = {};
// var a = this.serializeArray();
$(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select').each(function() {
if ($(this).attr('type') == 'hidden') { //if checkbox is checked do not take the hidden field
var $parent = $(this).parent();
var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
if ($chb != null) {
if ($chb.prop('checked')) return;
}
}
if (this.name === null || this.name === undefined || this.name === '')
return;
var elemValue = null;
if ($(this).is('select'))
elemValue = $(this).find('option:selected').val();
else elemValue = this.value;
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(elemValue || '');
} else {
o[this.name] = elemValue || '';
}
});
return o;
}
Here is what I use for this situation as a module (in my formhelper.js):
define(function(){
FormHelper = {};
FormHelper.parseForm = function($form){
var serialized = $form.serializeArray();
var s = '';
var data = {};
for(s in serialized){
data[serialized[s]['name']] = serialized[s]['value']
}
return JSON.stringify(data);
}
return FormHelper;
});
It kind of sucks that I can't seem to find another way to do what I want to do.
This does return this JSON for me:
{"first_name":"John","last_name":"Smith","age":"30"}
Using Underscore.js:
function serializeForm($form){
return _.object(_.map($form.serializeArray(), function(item){return [item.name, item.value]; }));
}
Using jQuery and avoiding serializeArray
, the following code serializes and sends the form data in JSON format:
$("#commentsForm").submit(function(event){
var formJqObj = $("#commentsForm");
var formDataObj = {};
(function(){
formJqObj.find(":input").not("[type='submit']").not("[type='reset']").each(function(){
var thisInput = $(this);
formDataObj[thisInput.attr("name")] = thisInput.val();
});
})();
$.ajax({
type: "POST",
url: YOUR_URL_HERE,
data: JSON.stringify(formDataObj),
contentType: "application/json"
})
.done(function(data, textStatus, jqXHR){
console.log("Ajax completed: " + data);
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log("Ajax problem: " + textStatus + ". " + errorThrown);
});
event.preventDefault();
});
My contribution:
function serializeToJson(serializer){
var _string = '{';
for(var ix in serializer)
{
var row = serializer[ix];
_string += '"' + row.name + '":"' + row.value + '",';
}
var end =_string.length - 1;
_string = _string.substr(0, end);
_string += '}';
console.log('_string: ', _string);
return JSON.parse(_string);
}
var params = $('#frmPreguntas input').serializeArray();
params = serializeToJson(params);
Well, here's a handy plugin for it: https://github.com/macek/jquery-serialize-object
The issue for it is:
Moving ahead, on top of core serialization, .serializeObject will support correct serializaton for boolean and number values, resulting valid types for both cases.
Look forward to these in >= 2.1.0
Found one possible helper:
https://github.com/theironcook/Backbone.ModelBinder
and for people who don't want to get in contact with forms at all: https://github.com/powmedia/backbone-forms
I will take a closer look at the first link and than give some feedback :)
참고URL : https://stackoverflow.com/questions/11338774/serialize-form-data-to-json
'IT' 카테고리의 다른 글
파이썬에서 0xbin ()이 False를 반환하는 이유는 무엇입니까? (0) | 2020.05.12 |
---|---|
Java의 클래스 경로에서 자원을로드하는 URL (0) | 2020.05.12 |
Javascript를 사용하여 현재 도메인 이름 가져 오기 (경로 등이 아님) (0) | 2020.05.12 |
대화 상자에서 편집 텍스트 상자를 만드는 방법 (0) | 2020.05.12 |
자바 추상 인터페이스 (0) | 2020.05.12 |