AJAX-使用AJAX将敲除的可观察对象作为JSON对象发送到服务器 [英] AJAX - Sending knockout observables as JSON object to server using AJAX
本文介绍了AJAX-使用AJAX将敲除的可观察对象作为JSON对象发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以JSON对象的形式向我的服务器发送绑定到特定可观察到的表单字段,但是我在服务器端收到了空的JSON字符串.我不想发送整个视图模型来完成此任务. 这是我到目前为止使用的JavaScript:
I am trying to send form fields which are bound to particular observable to my server in the form of JSON object but I receive empty JSON string at server side. I do not want to send the entire view model to accomplish this task. this is the javascript i have so far:
$(document).ready(function(){
ko.applyBindings(new AddSubjectKo());
});
function AddSubjectKo()
{
var self=this;
self.name = ko.observable();
self.quiz = ko.observable();
self.ass = ko.observable();
self.oht = ko.observable();
self.sess = ko.observable();
self.ese = ko.observable();
self.SubjectAdded=function()
{
$.ajax({
url: "api/courses",
type: "post",
data: formToJSON(),
contentType: "application/json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
function formToJSON() {
alert(self.name());
return JSON.stringify({
"name": self.name,
"quiz": self.quiz,
"ass": self.ass,
"oht": self.oht,
"sess": self.sess,
"ese": self.ese,
});
}
}
//$("#alert").slideDown();
}
推荐答案
您可以为此使用ko.toJSON
函数:
function AddSubjectKo()
{
var self=this;
self.name = ko.observable();
self.quiz = ko.observable();
self.ass = ko.observable();
self.oht = ko.observable();
self.sess = ko.observable();
self.ese = ko.observable();
self.SubjectAdded=function()
{
$.ajax({
url: "api/courses",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
这篇关于AJAX-使用AJAX将敲除的可观察对象作为JSON对象发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文