Ajax 调用自写的webservice


1、新建一个AJAXEnabledWebSite
2、“添加新项”--“SimpleService.asmx”,在SimpleService.cs添加代码:
[System.Web.Script.Services.ScriptService()]


然后把原来的HelloWorld方法改为SayHello()方法
SimpleService.cs完整代码如下:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// SimpleService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class SimpleService : System.Web.Services.WebService {

    public SimpleService () {

        //如果使用设计的组件,请取消注释以下行
        //InitializeComponent();
    }

    [WebMethod]
    public string SayHello(string Name)
    {
        return "Hello: "+Name;
    }
   
}

3、在Default.aspx添加input(Text)和input(Button)两个控件。双击button,
在<script language="javascript" type="text/javascript">...</script>中添加javascript处理代码
Default.aspx完整代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
<script language="javascript" type="text/javascript">
<!--

function Button1_onclick()
{

  ret=SimpleService.SayHello(document.getElementById('Text1').value, OnComplete, OnTimeOut, OnError);
  return(true);

}

function OnComplete(arg) {
alert(arg);
}

function OnTimeOut(arg) {
alert("TimeOut encountered when calling Say Hello.");
}

function OnError(arg) {
alert("Error encountered when calling Say Hello.");
}


// -->
</script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" >
        <Services>
        <asp:ServiceReference Path="SimpleService.asmx" />
       
        </Services>
       </asp:ScriptManager>
       
        <br />
        <div>
            <input id="Text1" type="text" />&nbsp;<br />
            <br />
            <input id="Button1" style="width: 200px" type="button" value="SayHello" language="javascript" onclick="return Button1_onclick()" /></div>
    </form>   
</body>
</html>

 

4、完成,详细信息请看http://asp.net/learn/ajax-videos/中的video5。 

你可能感兴趣的:(JavaScript,Ajax,function,webservice,input,button)