假设有一个基于.Net的Web Service,其名称为SaveProduct
POST /ProductService.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "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 OK Content-Type: text/xml; charset=utf-8 Content-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/
使用JQuery的Ajax调用SOAP-XML Web Services(Call SOAP-XML Web Services With jQuery Ajax)(译+摘录)
时间: 2024-10-05 08:47:09