jQuery调用WCF服务的设置请参考:jQuery调用WCF需要注意的一些问题。
WCF服务接口代码示例:
[ServiceContract]
public interface ICourseService
{
[OperationContract]
bool Create(Course course);
}
public interface ICourseService
{
[OperationContract]
bool Create(Course course);
}
客户端调用代码示例:
<
script type
=
"
text/javascript
"
src
=
"
/script/jquery.json-2.2.min.js
"
><
/
script>
< script type = " text/javascript " >
function create_course() {
var course = {};
course.Title = $( " #course_title " ).val();
course.CategoryId = $( " #course_category " ).val();
course.Frequency = $( " #course_frequency " ).val();
course.Alias = $( " #course_alias " ).val();
course.Description = $( " #course_desc " ).val();
course.IsPublish = $( " #is_publish " ).attr( " checked " ).toString();
var jsonCourse = $.toJSON(course);//代码1
var jsonCourse2 = '{"course":' + jsonCourse + '}' ;//代码2
$.ajax({
type: " POST " ,
url: " /wcf/CourseService.svc/Create " ,
data: jsonCourse2,
contentType: " application/json; charset=utf-8 " ,
dataType: " json " ,
success: function (data) {
},
error: function (xhr) {
debugger ;
}
});
}
< / script>
< script type = " text/javascript " >
function create_course() {
var course = {};
course.Title = $( " #course_title " ).val();
course.CategoryId = $( " #course_category " ).val();
course.Frequency = $( " #course_frequency " ).val();
course.Alias = $( " #course_alias " ).val();
course.Description = $( " #course_desc " ).val();
course.IsPublish = $( " #is_publish " ).attr( " checked " ).toString();
var jsonCourse = $.toJSON(course);//代码1
var jsonCourse2 = '{"course":' + jsonCourse + '}' ;//代码2
$.ajax({
type: " POST " ,
url: " /wcf/CourseService.svc/Create " ,
data: jsonCourse2,
contentType: " application/json; charset=utf-8 " ,
dataType: " json " ,
success: function (data) {
},
error: function (xhr) {
debugger ;
}
});
}
< / script>
上面代码红色字体部分:
代码1是通过jquery-json插件将JavaScript对象转换为Json格式。
代码2是将代码1得到的Json格式转换为WCF服务接口所需的Json格式,实际格式是:
{"course":{"Title":"test","CategoryId":"1","Frequency":"10","Alias":"test","Description":"testtest","IsPublish"
:"true"}}
参考文章:
Passing JSON serialized objects to a WCF service with jQuery