【菜鸟学WCF】使用ScriptManager+Ajax调用本地WCF服务

前端之家收集整理的这篇文章主要介绍了【菜鸟学WCF】使用ScriptManager+Ajax调用本地WCF服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

程序很简单,但是后面遇到诡异的事情了,先看源代码文件结构吧。

具体过程是:创建WebApplication空项目-->添加“启用了Ajax的WCF服务”-->添加“WebFrom1.aspx",然后就是在Service1.svc.cs 和 WebForm1.aspx.cs中添加代码,其他的什么都不用添加和更改。

@H_301_5@

@H_301_5@

服务中添加代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace WebApplication1
{
    //这里必须写命名空间,不要空着
    [ServiceContract(Namespace = "GLM")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
        // 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
        // 要创建返回 XML 的操作,
        //     请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     并在操作正文中包括以下行:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public string SayHello(string name)
        {
            // 在此处添加操作实现
            //return string.Format("hello world: {0}",name);
            return string.Format("hello,name={0}",name);
        }      
    }
}
@H_301_5@ WebFrom中添加代码如下:

@H_301_5@

@H_301_18@<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function test() { var client = new GLM.Service1(); var strName = "Jack"; client.SayHello(strName,OnComplete,OnError); } function OnComplete(result) { alert(result); } function OnError(result) { alert("Error"); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/Service1.svc" /> </Services> </asp:ScriptManager> <div> <input id="button1" type="button" value="click" onclick="test();" /> </div> </form> </body> </html> @H_301_5@ 这样代码已经OK了,程序是没有任何问题的。网上有很多例子都是这样的,但是我运行为什么有问题呢?

原来是这样的,我的默认浏览器是360的,我的操作是这样的,右键WebForm1,在浏览器中查看(默认打开的是360浏览器),然后把url复制粘贴到Firefox浏览器中,此时在firefox中运行是没问题的,但是当我把Service1中的代码修改后,直接刷新firefox,程序没有任何反映,然后我就去修改代码查错,未果。

解决办法是,重复刚开始的操作,右键WebForm1,在浏览器(默认360浏览器)中查看,此时再刷新firefox就没问题了。问题应该这样解释吧,当修改Service1的代码后,服务就自动停止了,直接刷新浏览器是不能开始服务的,而应该让VS去启动程序才会开启服务。

猜你在找的Ajax相关文章