如何用JavaScript調用Web服務——callService/useService
Web服務在分布式架構中起著重要的角色,在學習Web服務中,對Web Service的一些調用服務的方法做了一些整理。今天主要講通過JavaScript中的兩個方法——useService和callService來調用一個已存在的Web服務。
首先,看一下callService這個方法的語法:
iCallID是調用服務后返回的ID。
sElementID是useService方法的一個控件元素ID。稍后講如何用userServie。
sFriendlyName是服務名,比如.NET中Default.asmx,則這里是Default。
oCallHandler是處理響應結果的回調函數,因為有些請求無需關注響應結果,在這里是可選參數。
funcOrObj是web服務中的方法,在.NET中便是標有[WebMethod]的一些公用方法。
oParam是Web Method中的參數,可以是0,1,2,…個參數。
以下是做的一個例子:
function loginRequest() {
//服務Default.asmx, 方法CheckLoginByIO
iCallID = service.Default.callService(loginResponse, "CheckLoginByIO", userid.value, userpwd.value, "127.0.0.1");
}
//響應登陸
function loginResponse(res) {
//調用服務出錯
if (res.error) {
loginError.innerText = res.errorDetail.string;
}
else if (res.value.IsError) {//服務后來業務出錯
loginError.innerText = res.value.ErrorMessage;
}
else if (res.value.IsLogin) {//登陸成功
loginError.innerText = "login successfully,and your name is " + res.value.UserName;
}
else {//登陸失敗
loginError.innerText = "login failed, username or password is incorrect.";
}
}
注意,如果你想知道res.value里有哪些參數,而又不知道業務邏輯那邊到底返回了什么參數給你,你直接用Visual Studio 2008可以調試,不要忘了,JavaScript在IDE里的斷點調試功能也是無比強大的,不遜于C#.
鑒于對useService的用法,下面順便講一下createCallOptions:
//請求執行SQL語句方法
function executeSQLRequest() {
var co = serviceZivsoft.createCallOptions(); //createCallOptions
co.funcName = "ExecuteSql";//web服務方法名
iCallID = serviceZivsoft.Default.callService(executeSQLResponse,co,sql.value);
}
//響應執行SQL語句方法
function executeSQLResponse(res) {
if (res.error) {
Span1.innerText = res.errorDetail.string;
}
else {
//返回數據庫表記錄影響條數
Span1.innerText = res.value;
}
}
其次,看一下useService如何使用。
useService剛開始讓我費解的是哪里來的這個方法,后來發現我們需要去微軟官方上下載一個叫webservice.htc的文件。
下載完這個文件,將其放到根目錄下,在你的html里寫上這樣一段代碼就輕松搞定:
其實,這是我個人風格,我喜歡在onload時初始化web服務,初始化代碼如下:
//=====================================
// 初始化對Web服務的調用
// Autor: Lihua
// Url: http://www.zivsoft.com
//=====================================
function init() {
//由于我的Web服務在同一個項目,所以用了相對目錄
serviceZivsoft.useService("Default.asmx?WSDL", "Default");
}
關于useService更詳細的解釋,可以去MSDN上查閱,用法還是比較簡單的。
最后,給一個完整的HTML如下:
<head>
<title>采用userSErvice調用.NET Web Services</title>
<script language="JavaScript" type="text/javascript">
var iCallID;
//=====================================
// 初始化對Web服務的調用
// Autor: Lihua
// Url: http://www.zivsoft.com
//=====================================
function init() {
//由于我的Web服務在同一個項目,所以用了相對目錄
serviceZivsoft.useService("Default.asmx?WSDL", "Default");
}
function Add() {
//iCallID = sElementID.sFriendlyName.callService([oCallHandler], funcOrObj, oParam);
//iCallID: is the returned ID of the service call.
//In case of asynchronous call, this ID should be matched with the ID returned as a property of the result object.
//Only when matched can the result object be associated with this service call.
iCallID = serviceZivsoft.Default.callService(mathResults, "Add", a.value, b.value);
}
function mathResults(result) {
// if there is an error, and the call came from the call() in init()
if (result.error) {
// Pull the error information from the event.result.errorDetail properties
var xfaultcode = result.errorDetail.code;
var xfaultstring = result.errorDetail.string;
var xfaultsoap = result.errorDetail.raw;
// Add code to handle specific error codes here
lblError.innerHTML = "ERROR. Method call failed!"
+ "<br/>iCallID:" + iCallID
+ "<br/>Fault Code: " + xfaultcode
+ "<br/>Fault String:" + xfaultstring
+ "<br/>SOAP Data:" + xfaultsoap
+ "<br/>Result:" + result.value;
}
// if there was no error
else {
// Show the arithmetic
c.value = result.value;
}
}
//請求登陸
//--------------ZIVSOFT.COM---------------
//--------------Lihua Zhou----------------
function loginRequest() {
//服務Default.asmx, 方法CheckLoginByIO
iCallID = serviceZivsoft.Default.callService(loginResponse, "CheckLoginByIO", userid.value, userpwd.value, "127.0.0.1");
}
//響應登陸
//--------------ZIVSOFT.COM---------------
//--------------Lihua Zhou----------------
function loginResponse(res) {
//調用服務出錯
if (res.error) {
loginError.innerText = res.errorDetail.string;
}
else if (res.value.IsError) {//服務后來業務出錯
loginError.innerText = res.value.ErrorMessage;
}
else if (res.value.IsLogin) {//登陸成功
loginError.innerText = "login successfully,and your name is " + res.value.UserName;
}
else {//登陸失敗
loginError.innerText = "login failed, username or password is incorrect.";
}
}
</script>
</head>
<body onload="init()" id="serviceZivsoft" style="behavior: url(webservice.htc)">
<input id="a" value="2" />+
<input id="b" value="3" />=
<input id="c" />
<input type="button" value="compute" onclick="Add();" />
<p>
<span id="lblError"></span>
</p>
<hr />
<input id="userid" />
<input id="userpwd" type="password" />
<input type="button" value="login" onclick="loginRequest();" />
<p>
<span id="loginError"></span>
</p>
</body>
</html>
補充講一下用Post方法調用.NET Web Services,調用方式如下:
<body>
<form action="http://172.25.142.27/default.asmx/Add" method="post">
<input name="x" />
<input name="y" />
<input type="submit" value="Enter" />
</form>
</body>
</html>
另外,用心的朋友會注意到,默認情況下,.NET Web Services在遠程機器不能使用POST來調用遠程WEB服務,除非在WEB服務配置web.config中設置:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
如果沒有設置,你將會得到下面這個錯誤: The test form is only available for requests from the local machine.
想嘗試的朋友,可以用這個服務: http://www.w3schools.com/webservices/tempconvert.asmx
The following shows 倒計時.
<div id="divdown1"/>
<script language="javascript" type="text/javascript">
var interval = 1000;
function ShowCountDown(year,month,day,divname)
{
var now = new Date();
var endDate = new Date(year, month-1, day);
var leftTime=now.getTime()-endDate.getTime();
var leftsecond = parseInt(leftTime/1000);
var day1=Math.floor(leftsecond/(60*60*24));
var hour=Math.floor((leftsecond-day1*24*60*60)/3600);
var minute=Math.floor((leftsecond-day1*24*60*60-hour*3600)/60);
var second=Math.floor(leftsecond-day1*24*60*60-hour*3600-minute*60);
var cc = document.getElementById(divname);
if(hour<10){hour="0"+hour;}
if(minute<10){minute="0"+minute;}
if(second<10){second="0"+second;}
cc.innerHTML="第"+day1+"天 "+hour+"時"+minute+"分"+second+"秒";
}
window.setInterval(function(){ShowCountDown(1982,10,20,'divdown1');}, interval);
</script>
本文鏈接:http://www.rzrgm.cn/architect/archive/2009/05/14/1456818.html
關于作者:http://www.zivsoft.com/
浙公網安備 33010602011771號