|
Posted on
2008-09-02 17:05
飛雪飄寒
阅读( 4370)
评论()
编辑
收藏
举报
最近在项目中需要使用javascript调用webservice,从中遇到了几个问题,如果哪位高手知道的话,麻烦帮忙解答一下。
1、在网上找了好久,没找到webbehavior.htc文件的下载地址;
2、如何解决javascript调用webservice的跨域问题;
最近在项目中需要使用javascript调用webservice,从中遇到了几个问题,如果哪位高手知道的话,麻烦帮忙解答一下。
1、在网上找了好久,没找到webbehavior.htc文件的下载地址;
2、如何解决javascript调用webservice的跨域问题;
下面是自己在网上收集整理的javascript调用webservice的实现方式:
方法一、(自己实现,所遇问题:不能解决跨域的问题)
当flag=SOAPClient.invoke("http://localhost/GZPI/PublicWebService/WriteGraduater.asmx" , "GetGraduaterPorcessInfo", pl, false) 时,调用没有任何问题;
当flag=SOAPClient.invoke("http://192.168.65.26/GZHR/WebServices/SYDWReturnDataService.asmx" , "ReceiveResult", pl, false)时,提示"没有权限"的错误!
<script language="javascript" src="soapclient.js" charset="gb2312"></script>
<script language="javascript" type="text/javascript">
function UseWebServices()
{
var idcode="440523197209085275"; //身份证号
var Isgz ="1"; //是否广州户口 公务员:是否广州市户口(0:是1:否) 事业单位:是否广州市户口(1:是2:否)
var flag = false;
var SysID=1; //系统ID,1表示高校毕业生系统,2表示人才引进系统;
if(Isgz=="1")
{
var pl = new SOAPClientParameters();
pl.add("user", {UserName:"gwy@900001",Password:"123456"} );
pl.add("idcode",idcode);
flag=SOAPClient.invoke("http://172.16.128.84:8089/GZPI/PublicWebService/WriteGraduater.asmx" , "GetGraduaterPorcessInfo", pl, false);
if(flag==false)
{
SysID=2;
flag=SOAPClient.invoke("http://172.16.128.84:8089/GZPI/PublicWebService/WritePerson.asmx" , "GetGraduaterPorcessInfo", pl, false);
}
alert(flag);
if(flag==true)
{
if(SysID==1)
{
return confirm('该人员已在高校毕业生系统中申报,是否继续?');
}
else
{
return confirm('该人员已在人才引进系统中申报,是否继续?');
}
}
}
}
function WebServices()
{
var reply
var flag=false;
var pl = new SOAPClientParameters();
pl.add("ID","111111" );
pl.add("Result","成功");
//pl.add("Reply",reply);
flag=SOAPClient.invoke("http://192.168.65.26/GZHR/WebServices/SYDWReturnDataService.asmx" , "ReceiveResult", pl, false);
alert(flag);
//alert(reply);
alert(pl[1]);
}
</script>
soapclient.js
function SOAPClientParameters()
{
var _pl = new Array();
this.add = function(name, value)
{
_pl[name] = value;
return this;
}
this.toXml = function()
{
var xml = "";
for(var p in _pl)
xml += "<" + p + ">" + SOAPClientParameters._serialize(_pl[p]) + "</" + p + ">";
return xml;
}
}
SOAPClientParameters._serialize = function(o)
{
var s = "";
switch(typeof(o))
{
case "string":
s += o.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); break;
case "number":
case "boolean":
s += o.toString(); break;
case "object":
// Date
if(o.constructor.toString().indexOf("function Date()") > -1)
{
var year = o.getFullYear().toString();
var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
var milliseconds = o.getMilliseconds().toString();
var tzminutes = Math.abs(o.getTimezoneOffset());
var tzhours = 0;
while(tzminutes >= 60)
{
tzhours++;
tzminutes -= 60;
}
tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
}
// Array
else if(o.constructor.toString().indexOf("function Array()") > -1)
{
for(var p in o)
{
if(!isNaN(p)) // linear array
{
(/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
var type = RegExp.$1;
switch(type)
{
case "":
type = typeof(o[p]);
case "String":
type = "string"; break;
case "Number":
type = "int"; break;
case "Boolean":
type = "bool"; break;
case "Date":
type = "DateTime"; break;
}
s += "<" + type + ">" + SOAPClientParameters._serialize(o[p]) + "</" + type + ">"
}
else // associative array
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">"
}
}
// Object or custom function
else
for(var p in o)
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">";
break;
default:
throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
}
return s;
}
function SOAPClient() {}
SOAPClient.invoke = function(url, method, parameters, async, callback)
{
if(async)
SOAPClient._loadWsdl(url, method, parameters, async, callback);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if(wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
// get namespace
var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", soapaction);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
}
xmlHttp.send(sr);
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
if(nd.length == 0)
{
if(req.responseXML.getElementsByTagName("faultcode").length > 0)
{
if(async || callback)
o = new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
else
throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
}
}
else
o = SOAPClient._soapresult2object(nd[0], wsdl);
if(callback)
callback(o, req.responseXML);
if(!async)
return o;
}
SOAPClient._soapresult2object = function(node, wsdl)
{
var wsdlTypes = SOAPClient._getTypesFromWsdl(wsdl);
return SOAPClient._node2object(node, wsdlTypes);
}
SOAPClient._node2object = function(node, wsdlTypes)
{
// null node
if(node == null)
return null;
// text node
if(node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdlTypes);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdlTypes);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdlTypes).toLowerCase().indexOf("arrayof") != -1;
// object node
if(!isarray)
{
var obj = null;
if(node.hasChildNodes())
obj = new Object();
for(var i = 0; i < node.childNodes.length; i++)
{
var p = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
obj[node.childNodes[i].nodeName] = p;
}
return obj;
}
// list node
else
{
// create node ref
var l = new Array();
for(var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
return l;
}
return null;
}
SOAPClient._extractValue = function(node, wsdlTypes)
{
var value = node.nodeValue;
switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdlTypes).toLowerCase())
{
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if(value == null)
return null;
else
{
value = value + "";
value = value.substring(0, (value.lastIndexOf(".") == -1 ? value.length : value.lastIndexOf(".")));
value = value.replace(/T/gi," ");
value = value.replace(/-/gi,"/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypesFromWsdl = function(wsdl)
{
var wsdlTypes = new Array();
// IE
var ell = wsdl.getElementsByTagName("s:element");
var useNamedItem = true;
// MOZ
if(ell.length == 0)
{
ell = wsdl.getElementsByTagName("element");
useNamedItem = false;
}
for(var i = 0; i < ell.length; i++)
{
if(useNamedItem)
{
if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("type") != null)
wsdlTypes[ell[i].attributes.getNamedItem("name").nodeValue] = ell[i].attributes.getNamedItem("type").nodeValue;
}
else
{
if(ell[i].attributes["name"] != null && ell[i].attributes["type"] != null)
wsdlTypes[ell[i].attributes["name"].value] = ell[i].attributes["type"].value;
}
}
return wsdlTypes;
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdlTypes)
{
var type = wsdlTypes[elementname] + "";
return (type == "undefined") ? "" : type;
}
// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
try
{
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
}
catch (ex) {}
// old XML parser support
return document.getElementsByTagName(tagName);
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function()
{
try
{
if(window.XMLHttpRequest)
{
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if(req.readyState == null)
{
req.readyState = 1;
req.addEventListener("load",
function()
{
req.readyState = 4;
if(typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
if(window.ActiveXObject)
return new ActiveXObject(SOAPClient._getXmlHttpProgID());
}
catch (ex) {}
throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
if(SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for(var i = 0; i < progids.length; i++)
{
try
{
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
方法二、(网上搜集,所遇问题:未能下载到webbehavior.htc文件)
1 、首先,要创建一个webservice,比如
<%@ WebService Language="C#" class=MyMath %>
using System;
using System.Web.Services;
public class MyMath {
[WebMethod]
public int add(int a, int b)
{
return a + b;
}
[WebMethod]
public int subtract(int a, int b)
{
return a - b;
}
}
然后发布,先得到其wsdl。
2、首先,我们要下载webbehavior.htc这个文件(可以到http://msdn.microsoft.com/downloads/samples/internet/behaviors/library/webservice/default.asp.)
去下载,然后放到你的web当前目录下
然后在要调用webserice的页面中,修改如下
<body>
<div id="addservice" style="behavior:url(webservice.htc)"></div>
</body>
这里我们将div id命名为有意义的名称,并且指定style为 webservice行为。接着,我们要书写javascript来调用webserice了:
首先,我们在javascript中,调用其wsdladdservice.useService("http://localhost/services/math.asmx?WSDL","MyMath");
使用id.useService(WSDLL路径,简单的命名方式);
我们之前设定的id是addservice,而为了给客户端调用方便,我们这里起了名称,叫MyMath。而为了保证能正确调用webserice,必须在body里的onload事件里,马上加载处理webservice调用的javascript,如下
<script language="JavaScript">
function init()
{
addservice.useService("http://localhost/services/math.asmx?WSDL","MyMath"); }
</script>
<body onload="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>
在上面,我们通过webservice行为,首先得到了返回webservice的wsdl,接下来我们要进行调用了,调用的格式如下: iCallID = id.FriendlyName.callService([CallbackHandler,] "MethodName", Param1, Param2, ...);
这里id是我们在div里设置的id,而FridndbyName是我们刚才为方面而起的命,这里就是MyMath了,而CallbackHandler是使用回调函数的过程名,如果无设置的话,则默认是使用onresult所调用的方法来进行处理,下文会讲到,而param1,,param2等则是说传入的参数了,如:
<SCRIPT language="JavaScript">
// All these variables must be global,
// because they are used in both init() and onresult().
var iCallID = ;
var intA = 5;
var intB = 6;
function init()
{
// Establish the friendly name "MyMath" for the WebServiceURL
service.useService("/services/math.asmx?WSDL","MyMath");
// The following method doesn't specify a callback handler, so onWSresult() is used
iCallID = service.MyMath.callService("add", intA, intB);
}
function onWSresult()
{
// if there is an error, and the call came from the call() in init()
if((event.result.error)&&(iCallID==event.result.id))
{
// Pull the error information from the event.result.errorDetail properties
var xfaultcode = event.result.errorDetail.code;
var xfaultstring = event.result.errorDetail.string;
var xfaultsoap = event.result.errorDetail.raw;
// Add code to handle specific error codes here
}
// if there was no error, and the call came from the call() in init()
else if((!event.result.error) && (iCallID == event.result.id))
{
// Show the arithmetic!
alert(intA + ' + ' + intB + ' = ' + event.result.value);
}
else
{
alert("Something else fired the event!");
}
}
</SCRIPT>
<body onload="init()">
<div id="service" style="behavior:url(webservice.htc)" onresult="onWSresult()">
</div>
</body>
注意,用onresult方式返回的话,要在div部分的onresult中指定处理的方法,这里是用onWsresult()方法,其中根据返回的信息来判断是否出错,出错的话则显示。
如果用回调的话,则如下处理
<SCRIPT language="JavaScript">
// All these variables must be global,
// because they are used in both init() and onResult().
var iCallID = ;
var intA = 5;
var intB = 6;
function init()
{
// Establish the friendly name "MyMath" for the WebServiceURL
service.useService("/services/math.asmx?WSDL","MyMath");
// The following uses a callback handler named "mathResults"
iCallID = service.MyMath.callService(mathResults, "add", intA, intB);
}
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
}
// if there was no error
else
{
// Show the arithmetic
alert(intA + ' + ' + intB + " = " + result.value);
}
}
</SCRIPT>
<body onload="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>
信息来源:http://www.cnblogs.com/xiaobaidhg/articles/681284.html
|