最近帮别人面试SharePoint Developer,问他们项目开发时他们都提到了在一个部署到SharePoint页面中用javascript调用SharePoint WebService, 之前一直用SharePoint Service/Client API开发, 用C#代码调用过WebService,但是没有用JS试过,今天试了下,发现点使用上的问题,不费话了,直接上图上代码.
1.先建一个ASP.NET的工程,下载一个jQuery类库添加到工程中,再在工程中添加一个WebService
2. 在WebService中添加以下代码
namespace WebApplication4
{
/// <summary>
/// Summary description for MyWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NETAJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string msg)
{
return msg;
}
}
}
[System.Web.Script.Services.ScriptService]这一句默认是注释掉的,在Jquery中调用WebService时,如果返回xml格式没有问题,如果想返回json对象,这句注释必须打开
建完的WebService如下:
3. Jquery中调用WebService:
<html>
<head>
<scriptsrc="jquery-1.10.2.min.js"type="text/javascript"></script>
</head>
<body>
<scripttype="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url:"/MyWebService.asmx/HelloWorld",
data: "msg=123",
//contentType:"application/x-www-form-urlencoded; charset=UTF-8",
dataType: "xml",
success: function (data,textStatus) {
if (textStatus =="success") {
alert($(data).text());
}
},
error: function (data, status,error) {
alert("error");
}
});
});
</script>
</body>
</html>
这种调用指定dataType是xml,它的意思是返回类型是xml类型,contentType不用指定(默认是application/x-www-form-urlencoded;charset=UTF-8)
下面看另一个返回格式-json
<html>
<head>
<script src="jquery-1.10.2.min.js"type="text/javascript"></script>
</head>
<body>
<scripttype="text/javascript">
$(document).ready(function () {
var pdata = { "msg":"hello" };
$.ajax({
type: "POST",
url: "/MyWebService.asmx/HelloWorld",
data: "{'msg':'123'}",
contentType:"application/json; charset=UTF-8",
dataType: "json",
success: function (data,textStatus) {
if (textStatus =="success") {
alert(data.d);
}
},
error: function (data, status,error) {
alert("error");
}
});
});
</script>
</body>
</html>
dataType返回的是json对象,必须指定contentType为 application/json; charset=UTF-8