Ajax调用WebService接口样例

时间:2022-10-27 06:17:08

在做手机端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:

Ajax调用WebService接口样例

查看Raw:

Ajax调用WebService接口样例

使用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);
}
});