龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

jQuery ajax调用WCF服务实例(2)

时间:2014-08-04 12:04来源:网络整理 作者:网络 点击:
分享到:
foreach (DataRow result in ds.Tables[0].Rows) { TestResultData result_data = new TestResultData { DeployDate = Convert.ToDateTime(result["StatTime"]).ToString(), ServerName = result["ComponentName"].T

                foreach (DataRow result in ds.Tables[0].Rows)
                {
                    TestResultData result_data = new TestResultData
                    {
                        DeployDate = Convert.ToDateTime(result["StatTime"]).ToString(),
                        ServerName = result["ComponentName"].ToString(),
                        Build = result["Build"].ToString(),
                        Result = result["Result"].ToString(),
                        ServerInformation = result["Versions"].ToString()
                    };

                    test_result_list.Add(result_data);
                }

                return test_result_list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}

三、浏览器请求WCF服务

基本上,$.ajax方法需要8个参数:type指定操作方法(如POST)、url指定WCF服务的地址、data是传给WCF的数据(也就是参数)、contentType指定data的格式(如json)和文字编码、dataType指定返回数据的格式、processData指示是否自动将数据处理成application/x-www-form-urlencoded格式、success和error属性指示操作成功或失败后的回调方法。

我们在脚本中定义如下全局变量,以便调用ajax时访问:

复制代码 代码如下:

var Type, Url, Data, ContentType, DataType, ProcessData;

我们编写一个CallService方法,该方法直接调用$.ajax方法,并使用上面定义的参数:

复制代码 代码如下:

function CallService() {
    $.ajax({
        type: Type,
        url: Url,
        data: Data,
        contentType: ContentType,
        dataType: DataType,
        processData: ProcessData,
        success: function (msg) {
            ServiceSucceded(msg);
        },
        error: ServiceFailed
    });
}

以下是调用服务的一个示例,该方法从Year、Month和Date文本框中获取用户输入的数据,并调用WCF服务请求数据:

复制代码 代码如下:

function WcfJson() {
    Type = "POST";
    Url = "http://localhost:8734/TableManagerIntegrationTestService/TestResultService/GetData";
    Data = '{"year":' + $("#Year").val() + ', "month":' + $("#Month").val() + ', "date":' + $("#Date").val() + '}';
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; varProcessData = true;

    CallService();
}

在数据请求成功后,会调用success参数指定的回调方法,在此我们就可以处理返回结果。

精彩图集

赞助商链接