JavaScript调用Web Services实现无刷新三联动

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() 
ExpandedBlockStart.gifContractedBlock.gif            
{
                service.useService(
"/Service1.asmx?WSDL","myselect");
                str_province
=service.myselect.callService(province_Result,"getProvince");
            }
useService 语法:
sElementID.useService(sWebServiceURL, sFriendlyName [, oUseOptions])
useService 参数:

sElementIDRequired. The of the element to which the behavior is attached.
sWebServiceURLRequired. 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 nameA 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 nameA Web Services Description Language (WSDL) file name. The WSDL file must have a .wsdl file extension.
Full file pathFull 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 pathA relative path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string.
sFriendlyNameRequired. String representing a friendly name for the Web Service URL.
oUseOptionsOptional. An instance of the object.

callService语法:
iCallID = sElementID.sFriendlyName.callService( [oCallHandler], fo, oParam)
callService参数:
sElementIDRequired. The of the element to which the behavior is attached.
sFriendlyNameRequired. The friendly name for the Web Service, which is defined by calling the method.
oCallHandlerOptional. Name of a script callback function that handles the results returned from this instance of the method call.
foRequired. One of the following possible values.
strFuncNameA String representing the name of the remote function being called. The String must be bounded by single or double quotation marks.
objCallA object, which has the necessary properties defined to call a remote function.
oParamRequired. 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
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public static string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        SqlConnection conn
=new SqlConnection(ConnectionString);

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


ContractedSubBlock.gifExpandedSubBlockStart.gif        
Component Designer generated code#region Component Designer generated code
        
        
//Required by the Web Services Designer 
        private IContainer components = null;
                
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>

        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Clean up any resources being used.
        
/// </summary>

        protected override void Dispose( bool disposing )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if(disposing && components != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                components.Dispose();
            }

            
base.Dispose(disposing);        
        }

        
        
#endregion

        
ContractedSubBlock.gifExpandedSubBlockStart.gif        
getProvince#region getProvince
        [WebMethod(
true)]
        
public string getProvince()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string sql="select * from province";
            SqlCommand cmd
=new SqlCommand(sql,conn); 

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

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

            
return s;
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
getCity#region getCity
        [WebMethod(
true)]
        
public string getCity(string provinceid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
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())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                s 
+= "," + dr["cityID"].ToString() + "|" + dr["city"].ToString();
            }

            
return s;
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
getArea#region getArea
        [WebMethod(
true)]
        
public string getArea(string cityid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
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())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                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">
ExpandedBlockStart.gifContractedBlock.gif        
<script language="javascript">
        
<!--            
            
var str_province;
            
var str_city;
            
var str_area;

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


            
function province_Result(result)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{                
                
if(!result.error)
ExpandedSubBlockStart.gifContractedSubBlock.gif              
{                  
                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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                  
var ary1 = piArray[i].toString().split('|');
                  document.all(
"select_province").options.add(new Option(ary1[1].toString(),ary1[0].toString()));
                }
                
              }

            }


            
function province_onchange() 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
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() 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
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)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if(!result.error)
ExpandedSubBlockStart.gifContractedSubBlock.gif              
{
                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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                  
var ary1 = piArray[i].toString().split("|");
                  document.all(
"select_city").options.add(new Option(ary1[1].toString(),ary1[0].toString()));
                }

              }

            }


            
function area_Result(result)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if(!result.error)
ExpandedSubBlockStart.gifContractedSubBlock.gif              
{
                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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                  
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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/262552.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ArcGIS server for java 安装配置一 续

今天又发生件奇怪的事&#xff0c;昨天配置好的server for java环境&#xff0c;开机后rest服务有无法访问了&#xff0c;反复重装了几次&#xff0c;发现安装后 8399端口可以 使用&#xff0c;但修改了server.xml后&#xff0c;重启发现端口有无法使用了&#xff0c;提示端口下…

python爬虫-异常处理

URLerror产生原因&#xff1a; 网络未连接&#xff08;即不能上网&#xff09;服务器不存在1 #-*-coding:utf-8-*- 2 import urllib2 3 requesturllib2.Request(http://www.wujiadong.com)#这是一个不能打开的网址 4 responseurllib2.urlopen(request) 5 htmlresponse.read() 6…

将给定数据源生成静态HTML页面持久化到项目之外的硬盘

一、java代码 设置好数据源map Map<String,String> mapnew HashMap<>();map.put("knowledgeName",tBasKnowledgebase.getKnowledgeName());map.put("htmlContent",tBasKnowledgebase.getHtmlContent());map.put("publishDate",new j…

qt qthead里如何响应信号_Qt 中的多线程技术(翻译)

原文链接Multithreading Technologies in Qt​doc.qt.io正文Qt 提供一系列的类与函数来处理多线程。Qt 开发者们可以使用下面四种方法来实现多线程应用。QThread: 底层 API 与可选的事件循环作为 Qt 进行线程控制的基石&#xff0c;每一个 QThread 实例都代表并控制着一个线程。…

SATA盘与SAS盘的区别

在过去的20年中&#xff0c;并行&#xff08;Paralle&#xff09;总线接口在存储市场上占据了主导的地位。但随着CPU时钟频率和内存带宽的不断提升&#xff0c;两种主要的并行总线接口技术ATA和SCSI逐渐显现出不足来。尽管ATA和SCSI均是并行总线接口&#xff0c;但是它们之间却…

如何彻底删除SVN中的文件和文件夹(附恢复方法)

在SVN中如果删除某个文件或文件夹也可以在历史记录中进行找回&#xff0c;有的时候需要彻底删除某些文件&#xff0c;即不希望通过历史记录进行恢复&#xff0c;需要在服务器上对SVN的数据进行重新整理这里假设SVN项目的目录为 /data/svn/project&#xff0c;我们想排除trunk/t…

Linux 技巧: Bash 测试和比较函数

http://www.ibm.com/developerworks/cn/linux/l-bash-test.html 转载于:https://www.cnblogs.com/daojian/archive/2012/07/16/2593960.html

页面调用系统window打印

一、 打印&#xff1a;直接页面调用window.print()&#xff0c;当前页面就会转换成打印页面 当前页面是使用HTML拼接成A4纸表格样式的展示&#xff1b; doPrint:function(type) {// this.centerDialogVisiblefalse;$(#button).hide();window.print();$(#button).show(); } 二、…

为什么只看重结果_猫很现实?猫只是看重结果

猫的智谋是许多家养宠物难以比拟的&#xff0c;这和猫的思维模式有关。和一些看重过程的动物不同&#xff0c;猫非常重视结果。这意味着&#xff0c;猫会通过自己的观察&#xff0c;通过结果来倒推过程&#xff0c;从而记住最佳的行动方案。铲屎官教给猫的一些方法&#xff0c;…

SQL Server 语句查询手册

建表&#xff1a; CREATE TABLE [DB.dbo].tableName (Stud_id int CONSTRAINT constraintName1 not null primary key, Name nvarchar(5) not null, Birthday datetime, Gender nchar(1), Telcode char(12), Zipcode char(6) CONSTRAINT constraintName2 CHECK(zipcode like…

Spring 3整合Quartz 2实现定时任务(转)

http://www.meiriyouke.net/?p82 最近工作中需要用到定时任务的功能&#xff0c;虽然Spring3也自带了一个轻量级的定时任务实现&#xff0c;但感觉不够灵活&#xff0c;功能也不够强大。在考虑之后&#xff0c;决定整合更为专业的Quartz来实现定时任务功能。 首先&#xff0c;…

OpenGL Shader基本概念

转载自&#xff1a;http://blog.csdn.net/lcphoenix/article/details/6574417 使用OpenGL创造的物体&#xff0c;在最终被绘制出来之前&#xff0c;有一个流水线处理过程&#xff0c;该过程被称为graphics pipeline,或者rendering pipeline&#xff0c;期间大部分工作由GPU执行…

android 编译之后黑屏_抖音BoostMultiDex:Android低版本上首次启动时间减少80%(一)...

我们知道&#xff0c;Android 低版本(4.X 及以下&#xff0c;SDK < 21)的设备&#xff0c;采用的 Java 运行环境是 Dalvik 虚拟机。它相比于高版本&#xff0c;最大的问题就是在安装或者升级更新之后&#xff0c;首次冷启动的耗时漫长。这常常需要花费几十秒甚至几分钟&…

[转]关于多线程并发:每个开发人员都应了解的内容(转自Mainz's)

Concurrency: What Every Dev Must Know About Multithreaded Apps 本文讨论: 多线程和共享内存线程模型争用及并发访问如何能够打破不变量作为争用标准解决方案的锁定何时需要锁定如何使用锁定&#xff1b;理解开销锁定如何能够各行其道十年前&#xff0c;只有核心系统程序员会…

Filter案例之登录验证

一、登录验证&#xff0c;权限控制 1、需求分析 其中&#xff0c;登录有关的资源被访问时要直接放行&#xff0c;不然会死循环&#xff1b; 2、代码实现 转载于:https://www.cnblogs.com/wmqiang/p/11604621.html

未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。

当用sqlserver 导入excel文件的时候&#xff0c;会出现未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。 解决办法&#xff1a;去http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe下载。然后安装就行…

js导出excel单元格内换行符代码_前端和excel的那些事

前端和 excel 的那点事在开发需求中&#xff0c;经常会遇到需要和excel相关的需求&#xff0c;毕竟不是所有人都是程序员&#xff0c;很多的业务都是通过excel去进行数据的整理归类计算的&#xff0c;excel中提供的一系列快捷功能&#xff0c;统计功能也非常的实用&#xff0c;…

C语言高级技术之--游戏属性修改器(背景故事)

前些天&#xff0c;由于看朋友在玩单机游戏仙剑3&#xff08;这么早的游戏&#xff0c;早不完了&#xff09;&#xff0c;看得我实在太累&#xff0c;问他为什么不找修改器之类的&#xff0c;那样轻松一些&#xff0c;他的回答让我很无语&#xff0c;他说&#xff1a;“老是下到…

CIO职业生涯如何进行三级跳

关于从技术员到CIO转型的&#xff0c;网上讨论的已经很多了。下面笔者结合自己的工作经历&#xff0c;谈谈自己在这方面的感受。概括的说来&#xff0c;我的CIO职业生涯&#xff0c;可以用“三级跳”来概括。借此&#xff0c;也给应届毕业生几个建议。  一级跳&#xff1a;MC…

Filter案例之敏感词过滤和代理模式

一、需求分析 二 、代理模式 1、概念 2、代码实现 代理对象可以强转为真实对象&#xff0c;即对应的接口类&#xff1b; 3、通过代理增强方法 其中&#xff0c;方法对象invoke真实对象&#xff0c;反射原理&#xff1b; 三、过滤敏感词汇案例代码实现 本地的字符流和字节流创建…