分享XmlHttpRequest調(diào)用Webservice的一點(diǎn)心得
代碼如下:
function getXmlHttp() {
var xmlHttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
return xmlHttp;
}
function webservice(url, action, data, success, error, complete, failed) {
var xmlHttp = getXmlHttp(); //獲取XMLHttpRequest對(duì)象
xmlHttp.open('POST', url + '/' + action, true); //異步請(qǐng)求數(shù)據(jù)
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
try {
if (xmlHttp.status == 200 && typeof (success) == 'function') {
success(xmlHttp.responseText);
}
else if ((xmlHttp.status / 100 == 4 || xmlHttp.status / 100 == 5) && typeof (error) == 'function') {
error(xmlHttp.responseText, xmlHttp.status);
}
else if (xmlHttp.status / 100 == 200 && typeof (complete) == 'function') {
complete(xmlHttp.responseText, xmlHttp.status);
}
else if (typeof (failed) == 'function') {
failed(xmlHttp.responseText, xmlHttp.status);
}
}
catch (e) {
}
}
}
xmlHttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlHttp.setRequestHeader('SOAPAction', action);
xmlHttp.send(data);
}
比如請(qǐng)求調(diào)用Webservice1中的HelloWorld方法:
webservice('/Webservice1.asmx','HelloWorld','{}',function (msg) { alert(msg); });
調(diào)用前請(qǐng)記得把Webservice1上面的 [System.Web.Script.Services.ScriptService] 取消注釋,調(diào)用后可以看到彈出警告窗口:{"d": "Hello World"}。把Content-Type設(shè)為text/xml時(shí),警告窗口的內(nèi)容變就變成了<?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">Hello World</string>。
這時(shí)候雖然參數(shù)“{}”還是JSON的形式請(qǐng)求卻是XML格式,但因?yàn)镠ello World沒(méi)有參數(shù),所以忽略了內(nèi)容的格式,能夠正常返回值。
如果修改服務(wù)端的HelloWorld方法,添加一個(gè)string類型的參數(shù)somebody。
[WebMethod]
public string HelloWorld(string somebody) {
return "Hello World&Hello, " + somebody + "!";
}
將請(qǐng)求端的Content-Type改回application/json,傳送參數(shù)改為{"somebody": "Krime"},調(diào)用后彈出窗口內(nèi)容變?yōu)閧d: "Hello World&Hello, Krime!"}。
但如果這時(shí)再直接把Content-Type改為text/xml,調(diào)用后服務(wù)器將會(huì)報(bào)錯(cuò):System.InvalidOperationException: 請(qǐng)求格式無(wú)效: text/xml; charset=UTF-8。 在 System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() 在 System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
于是我們把參數(shù)格式也修改一下,按照Webservice調(diào)試頁(yè)面的示例,將參數(shù)改為:
<?xml version="1.0" encoding="utf-8"?>
<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/">
<soap:Body>
<HelloWorld xmlns="http://tempuri.org/">
<somebody>Krime</somebody>
</HelloWorld>
</soap:Body>
</soap:Envelope>
這樣應(yīng)該就能正常返回XML的結(jié)果了吧?結(jié)果卻出乎意料,服務(wù)器仍然報(bào)同樣的錯(cuò)誤。
折騰了很久后,幾乎要抓狂了,難道ASP.NET突然不認(rèn)識(shí)XML了?這個(gè)時(shí)候,再回去仔細(xì)看看Webservice調(diào)試頁(yè)面的示例,終于發(fā)現(xiàn)了一點(diǎn)問(wèn)題:
POST /WebServiceTest/Webservice1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"
<?xml version="1.0" encoding="utf-8"?>
<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/">
<soap:Body>
<HelloWorld xmlns="http://tempuri.org/">
<somebody>string</somebody>
</HelloWorld>
</soap:Body>
</soap:Envelope>
上面POST的地址后面并沒(méi)有像請(qǐng)求JSON數(shù)據(jù)時(shí)一樣加上/方法名,而SOAPAction的方法名前面還需要加上命名空間。于是修改XMLHttpRequest的請(qǐng)求頭,url和action做相應(yīng)修改,結(jié)果終于正常返回了XML的結(jié)果:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorldResponse xmlns="http://tempuri.org/"><HelloWorldResult>Hello World&Hello, Krime!</HelloWorldResult></HelloWorldResponse></soap:Body></soap:Envelope>
后來(lái)繼續(xù)測(cè)試,發(fā)現(xiàn)請(qǐng)求內(nèi)容類型為application/json時(shí),SOAPAction完全可以忽略不加,但是url后面一定要加上/方法名,否則服務(wù)器不會(huì)返回?cái)?shù)據(jù)。而請(qǐng)求text/xml時(shí),SOAPAction是必須的且前面要加上命名空間,url后面則不能有/方法名。
最后,經(jīng)過(guò)總結(jié),將代碼改成了最終的樣子:
function getXmlHttp() {
var xmlHttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
return xmlHttp;
}
function webservice(url, options) {
if (typeof (url) == 'object') { //將url寫(xiě)在options里的情況
options = url;
url = url.url;
}
if (!url) return;
if (options.dataType.toLowerCase() == 'json') { //請(qǐng)求JSON格式的數(shù)據(jù)時(shí),url后面需要加上“/方法名”
url = url + '/' + options.method;
}
var xmlHttp = getXmlHttp(); //獲取XMLHttpRequest對(duì)象
xmlHttp.open('POST', url, true); //異步請(qǐng)求數(shù)據(jù)
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
try {
if (xmlHttp.status == 200 && typeof (options.success) == 'function') {
options.success(xmlHttp.responseText);
}
else if ((xmlHttp.status / 100 == 4 || xmlHttp.status / 100 == 5) && typeof (options.error) == 'function') {
options.error(xmlHttp.responseText, xmlHttp.status);
}
else if (xmlHttp.status / 100 == 200 && typeof (options.complete) == 'function') {
options.complete(xmlHttp.responseText, xmlHttp.status);
}
else if (typeof (options.failed) == 'function') {
options.failed(xmlHttp.responseText, xmlHttp.status);
}
}
catch (e) {
}
}
}
xmlHttp.setRequestHeader('Content-Type', options.contentType); //設(shè)置請(qǐng)求頭的ContentType
xmlHttp.setRequestHeader('SOAPAction', options.namespace + options.method); //設(shè)置SOAPAction
xmlHttp.send(options.data); //發(fā)送參數(shù)數(shù)據(jù)
}
請(qǐng)求JSON數(shù)據(jù):
window.onload = function () {
var data = '{"somebody": "Krime"}';
var options = {
namespace: 'http://tempuri.org/',
method: 'HelloWorld',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
success: function (msg) {
alert(msg);
}
};
webservice('http://localhost:8003/WebServiceTest/Webservice1.asmx', options);
};
請(qǐng)求XML數(shù)據(jù):
window.onload = function () {
var data = '<?xml version="1.0" encoding="utf-8"?>'
+ '<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/">'
+ '<soap:Body>'
+ '<HelloWorld xmlns="http://tempuri.org/">'
+ '<somebody>Krime</somebody>'
+ '</HelloWorld>'
+ '</soap:Body>'
+ '</soap:Envelope>';
var options = {
namespace: 'http://tempuri.org/',
method: 'HelloWorld',
contentType: 'text/xml; charset=utf-8',
dataType: 'xml',
data: data,
success: function (msg) {
alert(msg);
}
};
webservice('http://localhost:8003/WebServiceTest/Webservice1.asmx', options);
};
測(cè)試情況正常。
需要注意的一點(diǎn)是,請(qǐng)求JSON數(shù)據(jù)時(shí),如果返回類型是DataTable是不行的,需要轉(zhuǎn)換成相應(yīng)數(shù)據(jù)實(shí)體類的List<>再返回。
在解決返回XML問(wèn)題的過(guò)程中,還找到另一種解決方法。具體操作時(shí),是將ContentType設(shè)為application/x-www-form-urlencoded,數(shù)據(jù)體不用JSON也不用XML格式的SOAP包,而是用類似QueryString的“arguement1=XXX&arguement2=XXX”。這個(gè)方法是模擬了窗體數(shù)據(jù)的HTTP POST格式,將每個(gè)控件值編碼為名稱=值對(duì)發(fā)送出去。
這種情況下的頁(yè)面地址后面也需要加上/方法名。
相關(guān)文章
深入理解JavaScript繼承的多種方式和優(yōu)缺點(diǎn)
這篇文章主要介紹了深入理解JavaScript繼承的多種方式和優(yōu)缺點(diǎn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05JS中如何實(shí)現(xiàn)點(diǎn)擊a標(biāo)簽返回頁(yè)面頂部的問(wèn)題
這篇文章主要介紹了JS中實(shí)現(xiàn)點(diǎn)擊a標(biāo)簽返回頁(yè)面頂部的問(wèn)題,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧2017-01-01echarts動(dòng)態(tài)渲染柱狀圖背景顏色及頂部數(shù)值方法詳解
在使用echarts時(shí),有時(shí)需要給柱狀圖設(shè)置背景,下面這篇文章主要給大家介紹了關(guān)于echarts動(dòng)態(tài)渲染柱狀圖背景顏色及頂部數(shù)值的相關(guān)資料,文中通過(guò)圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11js實(shí)現(xiàn)鼠標(biāo)移入移出卡片切換內(nèi)容
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)鼠標(biāo)移入移出卡片切換內(nèi)容,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10純js實(shí)現(xiàn)無(wú)限空間大小的本地存儲(chǔ)
這篇文章主要介紹了純js實(shí)現(xiàn)無(wú)限空間大小的本地存儲(chǔ)的功能,源碼和demo都放給大家,本文著重說(shuō)下實(shí)現(xiàn)的原理,具體的實(shí)踐擴(kuò)展小伙伴們自由發(fā)揮吧。2015-06-06JavaScript Fetch API請(qǐng)求和響應(yīng)攔截詳解
這篇文章主要為大家介紹了JavaScript Fetch API請(qǐng)求和響應(yīng)攔截詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11uploadify在Firefox下丟失session問(wèn)題的解決方法
在用uploadify上傳插件時(shí)遇到了一個(gè)問(wèn)題,在讀session時(shí)認(rèn)為沒(méi)有權(quán)限而被攔截了,后來(lái)在后臺(tái)打印登錄時(shí)產(chǎn)生session的id和上傳時(shí)讀取session的id,解決方法如下,感興趣的朋友可以了解下2013-08-08純javascript移動(dòng)優(yōu)先的幻燈片效果
這篇文章主要介紹了純javascript實(shí)現(xiàn)移動(dòng)優(yōu)先的幻燈片效果,感興趣的小伙伴們可以參考一下2015-11-11