JQuery訪問WebService(可訪問Java[Xfire])

來源:互聯網
上載者:User

最近有些時間學習了下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/裡面,方便管理防止丟失。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.