如何更改serializeObject输出格式?

时间:2015-10-14 17:47:18

标签: javascript

我是javascript的新手,无法找到解决方案。 我有以下代码。

<form class="edit-task-form">
        <legend>Create Task</legend>
        <label>Task</label>
        <input type="text" name="task" />
        <hr />
        <button type="submit" class="btn">Create</button>
    </form>
var taskDetails = $(ev.currentTarget).serializeObject();
var task = new Task;
task.save(taskDetails, {
    success: function(task) {
        alert(task.toJSON());
    }
});
console.log(taskDetails);
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if(o[this.name] !==undefined) {
        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;

输出为:Object {task:“fasdfasd”}

我希望它是:对象{“任务”:“fasdfasd”}

如何让“任务”出现在引号中?

非常感谢!

大卫

2 个答案:

答案 0 :(得分:0)

一个解决方案:

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if(o[this.name] !==undefined) {
        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;
}

&#13;
&#13;
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if(o[this.name] !==undefined) {
        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;
}
var val = $('.edit-task-form').serializeObject();
document.write('<pre>'+ JSON.stringify( val , null , ' ') + '</pre>')
$('form').submit(function(evt){
  evt.preventDefault();
document.write('<pre>'+ JSON.stringify( $(this).serializeArray() , null , ' ') + '</pre>')

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="edit-task-form">
        <legend>Create Task</legend>
        <label>Task</label>
        <input type="text" name="task" />
        <hr />
        <button type="submit" class="btn">Create</button>
    </form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你有这个功能:

int

您需要将其更改为:

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if(o[this.name] !==undefined) {
        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;

只需在键中添加引号

即可