zoukankan      html  css  js  c++  java
  • wcf

    开发使用javascript 和wcf交互的页面.

    首先在网站内添加一个wcf文件夹.

    首先,建立相应的服务.添加项目,选择启用了ajax的wcf服务.

    我这里是建立了个school服务.wcf文件夹下就生产了3个文件,一个是ISchool接口,一个school.svc,一个是school.svc.cs。

    服务主要是在cs文件中建立的。这个时候,配置文件会在system.serviceModel下生成对应的3个节点.services ,behaviors ,serviceHostingEnvironment,这时候,你要把behaviors 中behavior的<enableWebScript/>换成<webHttp/>,不然调用的时候会报错,没有找到服务的终结点.

    在服务中建立方法,这个不能是静态方法。

    为了测试方便,建立个student实体类.

    我首先建立个获取所有学生方法,代码如下

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "students")]
    public List<student> GetAllStudent()
    {
    List<student> students = new List<student> { new student("001", " 张三", 22), new student("002", "李四", 21) };
    return students;
    }

    这里,WebInvoke重写了调用服务时的一些属性,method是客户端调用的方式,第二个是表示输出的是json对象,默认的会是xml,第三个是服务的地址.客户端的url会是/wcf/school.svc/students,.

    客户端代码:

    $.ajax({
    url: '/wcf/school.svc/students',
    success: function (result) {
    if (result) {
    console.log(result);
    },
    error: function (error) { console.log(error); }
    });

    下面我们建立一个传递参数的。首先是get的:

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "student/{id}")]
    public student GetStudent(string id)
    {
    IEnumerable<student> students = new List<student>{ new student("001", " 张三", 22), new student("002", "李四", 21) };
    return students.First(p => p.StudentID == id);
    }

    这里唯一要注意的就是{id}要和方法里的参数名字一致。

    客户端代码:

    $.ajax({
    url: '/wcf/school.svc/student/001',
    success: function (result) {
    console.log("null", result);
    },
    error: function (error) { console.log(error); }
    });

    post的wcf

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "UpdateStudent")]
    public void UpdateStudent(student s)
    {
    }

    客户端代码:

    var student = { "StudentID": '004', "StudentName": "王五", "StudentAge": 24 };
     $.ajax({
    url: '/wcf/school.svc/updatestudent',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(student),
    contentType: 'application/json',
    success: function (result) {
    console.log("null", result);
    },
    error: function (error) { console.log(error); }
    });

    这个没有界面的演示,但在设置了断点后,调试过程中就能发现数据已经传到服务里面去了。

    为了简单,没有加上数据库方面的东西。

  • 相关阅读:
    Ionic4.x 中的button
    Ionic4.x 内置颜色
    Ionic4.x 中自定义公共模块
    Ionic4.x 新增底部 tabs 页面
    Ionic4.x 创建页面以及页面跳转
    Ionic4.x 项目结构简单分析
    判断Activty是否在前台运行
    Ionic 的安装运行
    Angular 自定义模块以及配置路由实现模块懒加载
    Angular 自定义模块
  • 原文地址:https://www.cnblogs.com/colorfullifes/p/2714633.html
Copyright © 2011-2022 走看看