基於JQuery的訪問WebService的代碼(可訪問Java[Xfire])

來源:互聯網
上載者:User

我仔細看看了看看幾個人的例子,發現了問題。眾所周知WebService是遵守SOAP協議的,為什麼例子都是JSON格式的參數傳遞?net WebService相容JSON格式,而Java的是標準WebService,不相容JSON。看來net害了大家啊。於是我仔細瞭解了WSDL檔案,做了個例子。下面只放關鍵代碼。 複製代碼 代碼如下:$(function () {
$("#btnWs").click(btnAjaxPost);
});

function btnAjaxPost(event) {
$.ajax({
type: "POST",
contentType:"text/xml",
url:"http://*****/WebServiceTest/services/HelloWorldService",
data:getPostData(),//這裡不該用JSON格式
dataType:'xml',//這裡設成XML或者不設。設成JSON格式會讓傳回值變成NULL
success: function(xml) {
//對結果做XML解析。
//瀏覽器判斷 (IE和非IE完全不同)
if($.browser.msie){
$("#result").append(xml.getElementsByTagName("ns1:out")[0].childNodes[0].nodeValue+"<br/>");
}
else{
$(xml).find("out").each(function(){
$("#result").append($(this).text()+"<br/>");
})
}
},
error: function(x, e) {
alert('error:'+x.responseText);
},
complete: function(x) {
//alert('complete:'+x.responseText);
}
});
}
//定義滿足SOAP協議的參數。
function getPostData()
{
//根據WSDL分析sayHelloWorld是方法名,parameters是傳入參數名
var postdata="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
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/\">";
postdata+="<soap:Body><sayHelloWorld xmlns=\"http://tempuri.org/\">";
postdata+="<parameters>"+$("#txtName").val()+"</parameters>";
postdata+="</sayHelloWorld></soap:Body>";
postdata+="</soap:Envelope>";
return postdata;
}

完整例子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.