前几天搞了个天气小插件来测试php soap 连接.net webservice 以及 JQuery Ajax 的简单应用!
我用的是php5.2自带有soap,要开启soap模块,(windows)只要在php.ini文件中把 ;extension=php_soap.dll 前的 ;去了,然后重启apache就可以了。
这个例子,我使用了一个天气预报的webservice 地是:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 以下是php代码:
文件名:webserviceclient.php
<?php
header("content-type:text/html; charset=utf-8");
//获取请求数据中city值
$city =$_GET["city"];
try {
$client=new SoapClient("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl",
array('encoding'=>'utf-8'));
/*
echo "<pre>";
//获取webservice提供的方法 返回数组,在不知道webservice有哪些方法可用时可以使用此方法获取webservice提供的方法!
var_dump($client->__getFunctions());
echo "</pre><p>";
print("<pre/>");
var_dump($client->__getTypes());
print("<pre/>");
*/
//
$parms = array("theCityName"=>$city);
//调用 getWeatherbyCityName 方法 返回天气情况是一个对象
//php调用.net的webservice时一定要用
//_call(string function_name, [, array arguments [, array options [, array input_headers [, array output_headers]]]]) 方法
//这里使用了 _call(string function_name,array arguments) 这个方法。
$arr=$client->__call('getWeatherbyCityName', array('parameters'=>$parms));
//获取返回对象中的数组数据
//使用_call方法获返回值是一个Object,以下是获取Object中的数组数据。
$obj2arr = $arr->getWeatherbyCityNameResult->string;
//返回Ajax请求数据,html格式的数据。
//天气预报图片可以在http://www.webxml.com.cn/WebServices/WeatherWebService.asmx上下载。
echo "<img src="."\""."./weather/b_".$obj2arr[8]."\""."/>";
echo "<img src="."\""."./weather/b_".$obj2arr[9]."\""."/>";
echo "<br>";
echo "<h4>".$obj2arr[1]."</h4>";
echo "<h4>".$obj2arr[6].$obj2arr[7]."</h4><h4>气温:".$obj2arr[5]."</h4>";
} catch (SOAPFault $e) {
print $e;
}
?>
OK,至此,php代码完成,我们可以通过访问 http://127.0.0.1/webserviceclient.php?city=广州 (本机为服务器而且php文档放在apache的htdocs目录下)来测试php代码!
接下来写前端html代码:
文件名:weather.html
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>天气预报 ajax testing</title>
<!--引用jquery -->
<script src="./js/jquery-1.5.2.js" type="text/javascript"></script>
</head>
<body>
输入城市:<input type="text" id = "city" onmouseout="get_inf()" />
<input type="button" id="submit" value="提交" onclick="get_inf()" />
<div id="content"></div>
<script type="text/javascript">
var data="";
function get_inf(){
var city = document.getElementById('city').value;
//调用JQuery的$.ajax()方法来实现ajax
$.ajax({
type: "GET", //声明请求方式
url: "webserviceclient.php", //相应请求的url
data: "city="+city, //请求参数
success: function(msg){ //请求成功返回,调用的方法
data=msg;
show_info();
}
});
}
function show_info(){
document.getElementById("content").innerHTML=data; //把数据显示在content的div中。
}
</script>
</body>
</html>
至此,小实验前端服务器端以及webservice都连起来了。下面来个测试的截图!
小结:php soap连接.net webservice时需要注意一定要用 _call()方法,在实验前看了网上一些调用php webservice和调用javawebservice的例子都无法调用到天气预报webservice的方法,后来通过URL才知道这是.net的webservice,通过网上搜索资料才知道如何调用!切记对症下药!

没有评论:
发表评论