在做手機端h5的應用時,通過Ajax調用http接口時沒啥問題的;但有些老的接口是用WebService實現的,也來不及改成http的方式,這時通過Ajax調用會有些麻煩,在此記錄具體實現過程。本文使用在線的簡體字和繁體字互轉WebService來演示,WebService地址為http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx。
1、使用SoapUI生成Soap消息
這里使用簡體轉繁體的方法toTraditionalChinese來生成Soap信息;該WebService支持Soap1.1、Soap1.2,下面生成的是Soap1.1的信息,Soap1.2一樣的生成。
查看XML:
查看Raw:
使用SoapUI可以很方便的測試WebService,不熟悉的同志可以了解下。
2、使用Jquery Ajax調用WebService
Soap1.1
function soapTest() { let data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webxml.com.cn/">' + '<soapenv:Header/>' + '<soapenv:Body>' + '<web:toTraditionalChinese>' + '<web:sText>小學</web:sText>' + '</web:toTraditionalChinese>' + '</soapenv:Body>' + '</soapenv:Envelope>'; $.ajax({
headers: {SOAPAction: 'http://webxml.com.cn/toTraditionalChinese'}, contentType: 'text/xml;charset="UTF-8"', dataType: 'xml', type: 'post', url: 'http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl', data: data, success: function(data) { let ss = $(data).find("toTraditionalChineseResult").first().text();//對應find方法中的值,不同的WebService可能會不同,需根據實際情況來填寫 alert(ss); } }); }
headers、contentType、data都是從SoapUI生成的信息里提取的。
Soap1.2
function soapTest12() { let data = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://webxml.com.cn/">' + '<soap:Header/>' + '<soap:Body>' + '<web:toTraditionalChinese>' + '<web:sText>大學</web:sText>' + '</web:toTraditionalChinese>' + '</soap:Body>' + '</soap:Envelope>'; $.ajax({ contentType: 'application/soap+xml;charset=UTF-8;action="http://webxml.com.cn/toTraditionalChinese"', dataType: 'xml', type: 'post', url: 'http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl', data: data, success:function(data) { let ss = $(data).find("toTraditionalChineseResult").first().text(); alert(ss); } }); }
contentType、data也都是從SoapUI生成的信息里提取的。
注:使用ie11可以正常調用,chrome會有跨域限制。
3、no SOAPAction header錯誤處理
用Ajax調用某些WebService的時候會報no SOAPAction header錯誤,缺少SOAPAction請求頭(targetNamespace+operation),增加即可。
$.ajax({
headers: {SOAPAction: 'http://webxml.com.cn/toTraditionalChinese'}
contentType: 'text/xml;charset="UTF-8"',
dataType: 'xml',
type: 'post',
url: 'http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl',
data: data,
success: function(data) {
let ss = $(data).find("toTraditionalChineseResult").first().text();//對應find方法中的值,不同的WebService可能會不同,需根據實際情況來填寫
alert(ss);
}
});