最近有些時間學習了下JQuery,發現有很多JQuery訪問.net WebService的例子。作為WebService這種介面應該是通用的,為什麼沒人關於Java的例子呢?這點引起我的興趣。
我仔細看看了看看幾個人的例子,發現了問題。眾所周知WebService是遵守SOAP協議的,為什麼例子都是JSON格式的參數傳遞?net WebService相容JSON格式,而Java的是標準WebService,不相容JSON。看來net害了大家啊。於是我仔細瞭解了WSDL檔案,做了個例子。下面只放關鍵代碼。
1 $(function () {
2 $("#btnWs").click(btnAjaxPost);
3 });
4
5 function btnAjaxPost(event) {
6 $.ajax({
7 type: "POST",
8 contentType:"text/xml",
9 url:"http://*****/WebServiceTest/services/HelloWorldService",
10 data:getPostData(),//這裡不該用JSON格式
11 dataType:'xml',//這裡設成XML或者不設。設成JSON格式會讓傳回值變成NULL
12 success: function(xml) {
13 //對結果做XML解析。
14 //瀏覽器判斷 (IE和非IE完全不同)
15 if($.browser.msie){
16 $("#result").append(xml.getElementsByTagName("ns1:out")[0].childNodes[0].nodeValue+"<br/>");
17 }
18 else{
19 $(xml).find("out").each(function(){
20 $("#result").append($(this).text()+"<br/>");
21 })
22 }
23 },
24 error: function(x, e) {
25 alert('error:'+x.responseText);
26 },
27 complete: function(x) {
28 //alert('complete:'+x.responseText);
29 }
30 });
31 }
32 //定義滿足SOAP協議的參數。
33 function getPostData()
34 {
35 //根據WSDL分析sayHelloWorld是方法名,parameters是傳入參數名
36 var postdata="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
37 postdata+="<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/\">";
38 postdata+="<soap:Body><sayHelloWorld xmlns=\"http://tempuri.org/\">";
39 postdata+="<parameters>"+$("#txtName").val()+"</parameters>";
40 postdata+="</sayHelloWorld></soap:Body>";
41 postdata+="</soap:Envelope>";
42 return postdata;
43 }
完整例子SVN地址:http://theyounglearningmaterials.googlecode.com/svn/trunk/JavaWebServices/WebServiceTest/
我以後所有學習的例子都會放在 http://theyounglearningmaterials.googlecode.com/svn/trunk/裡面,方便管理防止丟失。