做好了RESTful web 服务后,可以通过很多种方式向服务发起请求,本文仅介绍最简单的XMLHttpRequest发起请求方式。
客户端脚本如下:
<script type="text/javascript">
var xmlHttp = null; var url = ""; var content = "";
function PostXML() {
xmlHttp.onreadystatechange = show;
xmlHttp.open("POST", url);
xmlHttp.setRequestHeader("Content-Type", "application/xml");
xmlHttp.send(content);
}
function show() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
$("#txtResult").val(xmlHttp.responseText);
}
else {
$("#txtResult").val(xmlHttp.status.toString() + ":" + xmlHttp.statusText);
}
}
}
window.onload = function() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
url = $("#txtURL").val();
content = $("#txtRequest").val();
}
</script>
var xmlHttp = null; var url = ""; var content = "";
function PostXML() {
xmlHttp.onreadystatechange = show;
xmlHttp.open("POST", url);
xmlHttp.setRequestHeader("Content-Type", "application/xml");
xmlHttp.send(content);
}
function show() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
$("#txtResult").val(xmlHttp.responseText);
}
else {
$("#txtResult").val(xmlHttp.status.toString() + ":" + xmlHttp.statusText);
}
}
}
window.onload = function() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
url = $("#txtURL").val();
content = $("#txtRequest").val();
}
</script>
请求格式为:
<?xml version="1.0"?>
<VisitCostRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IndicationCode="indic" PatientStatus="1" TrialPhase="2" VisitCount="10">
<Country>
<Code>ddd</Code>
</Country>
</VisitCostRequest>
<VisitCostRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IndicationCode="indic" PatientStatus="1" TrialPhase="2" VisitCount="10">
<Country>
<Code>ddd</Code>
</Country>
</VisitCostRequest>
最终,通过页面控件调用PostXML方法即可。