Javascript调用webservice
前阵子做sharepoint开发时,需要用Javascript调用sharepoint的webservice,
开始打算自己写,后来发现网上有现成的,虽然直接直接拿来主义了,觉得
还是整理下如何使用Javascript调用webservice。
第一步先建立webservice, 就用.net默认生成的helloworld就可以了,但是有一个
需要注意的地方,如果用使用GET方法调用的话,在webconfig中加入如下的代码
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
</system.web>
可以对比修改webconfig前后webservice的提示页面(*.asmx?op=helloworld),
会发现修改后的多了个HTTP GET示例,如下图:
第二步就是写Javascript了,它的本质是通过使用浏览器封装的xmlhttprequest对象来实现的,
不同浏览器具体使用方法不同,我用的是IE,通常调用步骤
1创建xmlhttprequest实例
2设定xmlhttprequest属性
3和服务器通信
代码如下
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function WebServiceByGet() {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
//Webservice url
var URL = "http://localhost:1737/Service1.asmx/HelloWorld";
xmlhttp.Open("GET", URL, false);
xmlhttp.Send(null);
if (xmlhttp.status == 200) {
document.getElementById("txtResponse").value = xmlhttp.responseText;
} else {
alert(xmlhttp.statusText);
}
}
function WebServiceByPost() {
var data;
data = '<?xml version="1.0" encoding="utf-8"?>';
data = data + '<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/">';
data = data + '<soap:Body>';
data = data + '<HelloWorld xmlns="http://tempuri.org/">';
data = data + '</HelloWorld>';
data = data + '</soap:Body>';
data = data + '</soap:Envelope>';
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
var URL = "http://localhost:1737/Service1.asmx";
xmlhttp.Open("POST", URL, false);
xmlhttp.SetRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.SetRequestHeader("SOAPAction", "http://tempuri.org/HelloWorld");
xmlhttp.Send(data);
if (xmlhttp.status == 200) {
document.getElementById("txtResponse").value = xmlhttp.responseText;
} else {
alert(xmlhttp.statusText);
}
}
</script>
<input type="button" value="CallWebserviceByGet" οnclick="WebServiceByGet()"/>
<input type="button" value="CallWebserviceByPost" οnclick="WebServiceByPost()"/>
<input type="text" id = "txtResponse"/>
</body>
</html>
对了补充一点,上面两种方法返回的xml结构不同哦。