前面讲了那么多关于webservice的东西.现在来看一个具体的例子
这里我选用了使用http来调用webservice的方法
我使用的webservie地址是
http://www.wopos.com/webservice/weather.asmx
其中有一个getWeather的函数。我们可以从
http://www.wopos.com/webservice/weather.asmx?op=getWeather
中看到其协议格式。因为使用http的方法调用所以应该按照http post规定的格式传给webservice数据。并且按照http get格式接受并且解析数据。
具体的实验代码如下
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>New Page 1</title>
<style>
.WeatherReportTable
{
border-collapse: collapse;
font-family:Tahoma;
font-size:8pt;
color:#333333
}
</style>
<SCRIPT language="JavaScript">
function renderWeatherReport(data)
{
dataItems = data.split(",");
var tableHtml = '<table class ="WeatherReportTable" width="100%" border="0">';
for(var i = 0; i < dataItems.length;i++)
{
columnContents = dataItems[i].split("==");
//ignore the picture
//you can add as you want
if(columnContents [0] == '图1' || columnContents [0] == '图2')
{
continue;
}
var rowHtml = '<tr>';
rowHtml += '<td>';
rowHtml += columnContents[0] + '</td>';
rowHtml += '<td>' + columnContents[1] + '</td>';
rowHtml += '</tr>'
tableHtml += rowHtml;
}
tableHtml += '</table>';
console.innerHTML = tableHtml;
}
// Client invoke WebService use HTTP POST request and response
function GetWeatherReportHttpPOST()
{
var URL = "http://www.wopos.com/webservice/weather.asmx/getWeather";
var Params = "mCity=上海";// you can change your city name here,IN CHINESE ATTENTION!!!!
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.Open("POST",URL, false);
xmlhttp.SetRequestHeader ("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
xmlhttp.SetRequestHeader ("Content-Length",Params.length);
xmlhttp.send(Params);
var x = xmlhttp.responseXml;
//alert(x.text);
if(xmlhttp.status == 200)
{
renderWeatherReport(x.text);
}
else
{
console.innerHTML = xmlhttp.statusText;
}
}
window.onload = function()
{
GetWeatherReportHttpPOST();
}
</SCRIPT>
</head>
<body>
<div id="console">
</div>
</body>
</html>
需要注意的是.xmlhttp是不能垮域调用的~~上面的代码在ie中直接打开文件(就是从资源管理其中打开文件)是成功的~可是如果放在虚拟目录中用localhost域调用就不行(除非webservice也是在localhost域的)
本文介绍了一种通过HTTP调用WebService的方法,并提供了一个具体的示例。该示例使用JavaScript实现,展示了如何发送HTTP POST请求获取天气信息。
9214

被折叠的 条评论
为什么被折叠?



