【发布时间】:2013-01-24 04:36:09
【问题描述】:
我的任务是进行用户编辑。我这样做了。但我不能将值作为 json 对象传递。我怎样才能加入两个值。 我的第一个对象是
$.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 location = function() {
var self = this;
self.country = ko.observable();
self.state = ko.observable();
};
var map = function() {
var self = this;
self.lines = ko.observableArray([new location()]);
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.state() ? {
state: line.state().state,
country: line.country().country
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};
ko.applyBindings(new map());
});
我想把它连接起来。我试过了,但我得到了一个错误
$.ajax({
url: '/users/<%=@user.id%>',
dataType: 'json',
//async: false,
//contentType: 'application/json',
type: 'PUT',
data: {total_changes: JSON.stringify(dataToSave) + JSON.stringify($("#edit_user_1").serializeObject())},
//data:JSON.stringify(dataToSave),
//data:dataToSave,
success: function(data) {
alert("Successful");
},
failure: function() {
alert("Unsuccessful");
}
});
当我运行它时,它会在终端中显示类似这样的错误。
我该如何解决这个问题?
【问题讨论】:
-
你试过jQuery的扩展方法吗? api.jquery.com/jQuery.extend
-
@Nithin Viswanath 你有两个 json 对象,所以创建一个 jsonarray 并放置这两个对象。
-
JSONArray jArray = new JSONArray(); JSONObject json = new JSONObject(); json.put( , );// 放值 jArray.put(json);json = new JSONObject(); json.put( , );// 放值 jArray.put(json);
-
到底什么是“JSON 对象”? JSON 是 TEXT(字符串)。您可以从中创建一个 Javascript(!) 对象(反之亦然,“字符串化”一个 JS 对象),或使用字符串处理工具对其进行处理,或者从其他语言的 JSON 字符串创建对象,例如在红宝石。但是没有 JSON 对象。你可能认为我在吹毛求疵,但我不是——看来你想处理 JAVASCRIPT OBJECTS。如果你说“JSON”,听起来你想处理 STRINGS。
标签: javascript jquery html ajax json