標籤:style blog http color 使用 os io strong
假設有一個基於.Net的Web Service,其名稱為SaveProduct
POST /ProductService.asmx HTTP/1.1Host: localhostContent-Type: text/xml; charset=utf-8Content-Length: lengthSOAPAction: "http://sh.inobido.com/SaveProduct" <?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> <SaveProduct xmlns="http://sh.inobido.com/"> <productID>int</productID> <productName>string</productName> <manufactureDate>dateTime</manufactureDate> </SaveProduct> </soap:Body></soap:Envelope>
在用戶端用jQuery的ajax調用的代碼為
var productServiceUrl = ‘http://localhost:57299/ProductService.asmx?op=SaveProduct‘; // Preferably write this out from server side function beginSaveProduct(productID, productName, manufactureDate){ var soapMessage = ‘<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> <SaveProduct xmlns="http://sh.inobido.com/"> <productID>‘ + productID + ‘</productID> <productName>‘ + productName + ‘</productName> <manufactureDate>‘ + manufactureDate + ‘</manufactureDate> </SaveProduct> </soap:Body> </soap:Envelope>‘; $.ajax({ url: productServiceUrl, type: "POST", dataType: "xml", data: soapMessage, complete: endSaveProduct, contentType: "text/xml; charset=\"utf-8\"" }); return false;} function endSaveProduct(xmlHttpRequest, status){ $(xmlHttpRequest.responseXML) .find(‘SaveProductResult‘) .each(function() { var name = $(this).find(‘Name‘).text(); });}
說明:
- type: 發送的請求的類型-the type of request we‘re sending
- dataType: 發回的響應的類型- the type of the response will send back, 一般情況下可以是html, json等類型,但如果是一個SOAP web service,必須定義為 xml類型
- data: 發送給web service的實際資料
- complete: function (XMLHttpRequest, textStatus) { /* Code goes here */ }
- contentType: 請求的MIME content類型, 同理,如果是一個SOAP web service,必須定義為 “text/xml”
- endSaveProduct:現在XML資料就已經發送到web service了,一旦伺服器server接受到請求並進行處理,調用endSaveProduct方法
如用jQuery處理傳回的XML響應,必須理解SOAP reponse’s schema定義,SaveProduct的schema格式如下:
HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length <?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> <SaveProductResponse xmlns="http://sh.inobido.com/"> <SaveProductResult> <ID>int</ID> <Name>string</Name> <ManufactureDate>dateTime</ManufactureDate> </SaveProductResult> </SaveProductResponse> </soap:Body></soap:Envelope>
傳回的響應放在xmlHttpRequest的參數responseXML中,可以使用firebug或Dev. Tool查看,現在我們就可以使用jQuery來遍曆該XML的節點並處理資料了。
摘錄自:http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/