http://singlepine.cnblogs.com/articles/301009.html


使用微软提供的webservice.htc实现通过JavaScript调用WebService.
1.首先从微软网站上下载webservice.htc,我附件源代码也包含,不下载也可以
http://msdn.microsoft.com/workshop/author/webservice/webservice.htc
2.在网页BODY中添加一个DIV,实现对webservice.htc的引用

<div id="service" style="BEHAVIOR:url(webservice.htc)"></div>

3.编写JavaScript,实现对WebService的引用:

function window_onload() 
            {
                service.useService("/Service1.asmx?WSDL","myselect");
                str_province=service.myselect.callService(province_Result,"getProvince");
            }

useService 语法:
sElementID.useService(sWebServiceURL, sFriendlyName [, oUseOptions])
useService 参数:

sElementID Required. The of the element to which the behavior is attached.
sWebServiceURL Required. String specifying the URL of the Web Service, using one of the following path types. See the examples section, where several variations of this parameter are shown.

Web Service file name A Web service file, which has an .asmx file extension. This short form of the URL is sufficient, provided that the Web service is located in the same folder as the Web page using the WebService behavior. In this case, the ?WSDL query string is assumed by the behavior.
WSDL file name A Web Services Description Language (WSDL) file name. The WSDL file must have a .wsdl file extension.
Full file path Full path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string. Either a local file path or a URL can be specified.
Relative path A relative path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string.
sFriendlyName Required. String representing a friendly name for the Web Service URL.
oUseOptions Optional. An instance of the object.

callService语法:
iCallID = sElementID.sFriendlyName.callService( [oCallHandler], fo, oParam)
callService参数:

sElementID Required. The of the element to which the behavior is attached.
sFriendlyName Required. The friendly name for the Web Service, which is defined by calling the method.
oCallHandler Optional. Name of a script callback function that handles the results returned from this instance of the method call.
fo Required. One of the following possible values.

strFuncName A String representing the name of the remote function being called. The String must be bounded by single or double quotation marks.
objCall A object, which has the necessary properties defined to call a remote function.
oParam Required. One or more comma-delimited parameters, which are passed to the method name specified by fo.

4.建立WebService,代码如下

public class Service1 : System.Web.Services.WebService
    {
        public static string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        SqlConnection conn=new SqlConnection(ConnectionString);

        public Service1()
        {
            //CODEGEN: This call is required by the ASP.NET Web Services Designer
            InitializeComponent();
        }

        Component Designer generated code#region Component Designer generated code
        
        //Required by the Web Services Designer 
        private IContainer components = null;
                
        /**//// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        /**//// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if(disposing && components != null)
            {
                components.Dispose();
            }
            base.Dispose(disposing);        
        }
        
        #endregion
        
        getProvince#region getProvince
        [WebMethod(true)]
        public string getProvince()
        {
            string sql="select * from province";
            SqlCommand cmd=new SqlCommand(sql,conn); 

            cmd.Connection.Open();
            SqlDataReader dr=cmd.ExecuteReader();

            string s="";
            while(dr.Read())
            {
                s += "," + dr["provinceID"].ToString() + "|" + dr["province"].ToString();
            }
            return s;
        }

        #endregion

        getCity#region getCity
        [WebMethod(true)]
        public string getCity(string provinceid)
        {
            string str="select * from city where father = '"+provinceid+"'";
            SqlCommand cmd=new SqlCommand(str,conn); 

            cmd.Connection.Open();
            SqlDataReader dr=cmd.ExecuteReader();

            string s="";
            while(dr.Read())
            {
                s += "," + dr["cityID"].ToString() + "|" + dr["city"].ToString();
            }
            return s;
        }

        #endregion

        getArea#region getArea
        [WebMethod(true)]
        public string getArea(string cityid)
        {
            string str="select * from area where father='"+cityid+"'";
            SqlCommand cmd=new SqlCommand(str,conn); 

            cmd.Connection.Open();
            SqlDataReader dr=cmd.ExecuteReader();

            string s="";
            while(dr.Read())
            {
                s += "," + dr["areaID"].ToString() + "|" + dr["area"].ToString();
            }
            return s;
        }
        #endregion
    }

5.建立测试页面

<HTML>
    <HEAD>
        <title>jsWebServices</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        <script language="javascript">
        <!--            
            var str_province;
            var str_city;
            var str_area;

            function window_onload() 
            {
                service.useService("/Service1.asmx?WSDL","myselect");
                str_province=service.myselect.callService(province_Result,"getProvince");
            }

            function province_Result(result)
            {                
                if(!result.error)
              {                  
                document.all("select_province").length=0;                
                if(result.value.substring(0,1)==",")
                        result.value =result.value.substring(1,result.length);
                var piArray = result.value.split(',');
                for(var i=0;i<piArray.length;i++)
                {
                  var ary1 = piArray[i].toString().split('|');
                  document.all("select_province").options.add(new Option(ary1[1].toString(),ary1[0].toString()));
                }                
              }
            }

            function province_onchange() 
            {
                var province=document.getElementById("select_province");
                var pindex = province.selectedIndex;
                var pValue = province.options[pindex].value;
                var pText  = province.options[pindex].text;
                str_city=service.myselect.callService(city_Result,"getCity",pValue);
            }

            function city_onchange() 
            {
                var city=document.getElementById("select_city");
                var cindex = city.selectedIndex;
                var cValue = city.options[cindex].value;
                var cText  = city.options[cindex].text;
                str_area=service.myselect.callService(area_Result,"getArea",cValue);
            }

            function city_Result(result)
            {
                if(!result.error)
              {
                document.all("select_city").length=0;
                if(result.value.substring(0,1)==",")
                        result.value =result.value.substring(1,result.length);
                var piArray = result.value.split(",");
                for(var i=0;i<piArray.length;i++)
                {
                  var ary1 = piArray[i].toString().split("|");
                  document.all("select_city").options.add(new Option(ary1[1].toString(),ary1[0].toString()));
                }
              }
            }

            function area_Result(result)
            {
                if(!result.error)
              {
                document.all("select_area").length=0;
                if(result.value.substring(0,1)==",")
                        result.value =result.value.substring(1,result.length);
                var piArray = result.value.split(",");
                for(var i=0;i<piArray.length;i++)
                {
                  var ary1 = piArray[i].toString().split("|");
                  document.all("select_area").options.add(new Option(ary1[1].toString(),ary1[0].toString()));
                }
              }
            }
            //-->
        </script>
    </HEAD>
    <body MS_POSITIONING="GridLayout" onload="return window_onload()">
        <div id="service" style="BEHAVIOR:url(webservice.htc)"></div>
        <form id="Form1" method="post" runat="server">
            <SELECT id="select_province" onchange="province_onchange();" style="Z-INDEX: 101; LEFT: 8px; WIDTH: 128px; POSITION: absolute; TOP: 16px">
                <OPTION selected></OPTION>
            </SELECT><SELECT id="select_city" onchange="city_onchange();" style="Z-INDEX: 102; LEFT: 160px; WIDTH: 128px; POSITION: absolute; TOP: 16px">
                <OPTION selected></OPTION>
            </SELECT><SELECT id="select_area" style="Z-INDEX: 103; LEFT: 304px; WIDTH: 128px; POSITION: absolute; TOP: 16px">
                <OPTION selected></OPTION>
            </SELECT>
        </form>
    </body>
</HTML>

6.引用webservicers
7.数据库脚本

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[area]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[area]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[province]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[province]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[city]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[city]
GO

CREATE TABLE [dbo].[area] (
    [id] [int] NOT NULL ,
    [areaID] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [area] [nvarchar] (60) COLLATE Chinese_PRC_CI_AS NULL ,
    [father] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[province] (
    [id] [int] NOT NULL ,
    [provinceID] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL ,
    [province] [nvarchar] (40) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[city] (
    [id] [int] NOT NULL ,
    [cityID] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL ,
    [city] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [father] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]
GO

8.下载真实数据/Files/singlepine/area.rar
9.源代码下载/Files/singlepine/jsWebServices.rar

转载于:https://www.cnblogs.com/291099657/archive/2009/04/09/1432493.html

JavaScript调用Web Services实现无刷新三联动相关推荐

  1. Ajax实现无刷新三联动下拉框

    1.html代码 <HTML>     <HEAD>         <title>Ajax实现无刷新三联动下拉框</title>         &l ...

  2. 深入Atlas系列:Web Sevices Access in Atlas示例(4) - 使用HTTP GET调用Web Services方法...

    在之前的例子里,由于Atlas客户端在调用Web Services方法时总是使用了Sys.Net.ServiceMethod类,因此始终使用了HTTP POST方法与服务器端进行交互.POST方法有其 ...

  3. ASP调用web services

    代码  1     Function CallWebServices(sUrl, sMethodName, soapMessage, XmlString)  2         CallWebServ ...

  4. 全国省市县无刷新多级联动菜单

    全国省市县无刷新多级联动菜单 <html> <head> <title>省市县关联菜单</title> <meta http-equiv=&quo ...

  5. 轻松实现无刷新三级联动菜单[VS2005与AjaxPro]

    最近做一些网站程序,经常要用到多个下拉菜单选择,看了介绍开始用AjaxPro这个控件,感觉效果不错.以前使用过MagicAjax,很久不用了忘记了,最麻烦的就是在虚拟目录的时候比较麻烦,呵呵,在网上也 ...

  6. 实现无刷新DropDownList联动效果

    在做一个文章添加功能时,想在选择大类后,自动将其所属二级小类显示出来,使用DropDownList的SelectedIndexChanged事件可以很容易实现,但每次选择后页面总要刷新一次,让人感觉很 ...

  7. ajaxpro post html,轻松实现无刷新三级联动菜单[vs2005与ajaxpro]_ajax教程

    最近做一些网站程序,经常要用到多个下拉菜单选择,看了介绍开始用AjaxPro这个控件,感觉效果不错.以前使用过MagicAjax,很久不用了忘记了,最麻烦的就是在虚拟目录的时候比较麻烦,呵呵,在网上也 ...

  8. java dropdownlist_实现无刷新DropDownList联动效果

    在做一个文章添加功能时,想在选择大类后,自动将其所属二级小类显示出来,使用DropDownList的JavaScript 在做一个文章添加功能时,想在选择大类后,自动将其所属二级小类显示出来,使用Dr ...

  9. addoption php,无忧建站-ajax+php无刷新二级联动下拉菜单(省市联动)源码

    /** * ajax无刷新二级联动下拉菜单(省市联动) * * @author      arcow * @version     1.0 * @lastupdate  2005-12-29 * */ ...

最新文章

  1. 自定义html托管,10分钟搞定“傻瓜式”的静态网站搭建托管之旅
  2. HTML DOM Attribute 对象
  3. java自动生成代码原理_原来这就是Java代码生成器的原理啊,太简单了
  4. 巴巴腾机器人怎么开机_【巴巴腾智能机器人使用】_摘要频道_什么值得买
  5. 《转》cout和printf的混用而产生的顺序问题
  6. hadoop2.6.0安装详细步骤
  7. 相位噪声 matlab,相位噪声仿真方法.PDF
  8. Java 8中的可重复注释
  9. leetcode - 813. 最大平均值和的分组
  10. Docker 容器遇到的乱码问题
  11. mysql获取上月的某一天
  12. MySQL INSERT ... ON DUPLICATE KEY UPDATE语句
  13. 拿什么拯救Web时代的安全危机
  14. sql中concat函数_SQL中的CONCAT函数概述和示例
  15. STM32传感器外设集--心率模块(MAX30102)
  16. 通用安防摄像机通过RTSP转RTMP推流进行H5(RTMP/HLS)直播的方案
  17. 求字符串长度的函数的几种实现方法
  18. SQL 删除数据空格(Trim、RTrim、LTrim函数)
  19. CVPR2014 tracking
  20. 数字图像处理艺术化效果——彩色图像转化为灰度图像(黑白照片)

热门文章

  1. python小爬虫(爬取职位信息和博客文章信息)
  2. Opencv3编程入门学习笔记(五)之通道分离(split)与合并(merge)
  3. shell date常用运算命令
  4. html两个框架同时_两个框架的故事
  5. 华为2017年财报,为何6036亿销售收入,净利润才479亿?
  6. 在看世界杯的闲暇看看电视剧《长恨歌》
  7. 电子设计从零开始 第一章总结
  8. 快速傅里叶变换python_【原创】OpenCV-Python系列之傅里叶变换(三十八)
  9. 西门子plm_西门子的Teamcenter、TIA Portal、NX MCD是如何结合在一起的
  10. python采用编译型方式执行_Python程序的执行过程 解释型语言和编译型语言