1、Web.Config中增加如下红色标记部分配置:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<!--提供Ajax调用开始 -->
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
<!--提供Ajax调用结束-->
</system.web>
2、增加一个Tools类,如下代码:
public class Tools
{
public static void WriteResult(string callback, string result)
{
HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Write(callback + "(" + result + ")");
HttpContext.Current.Response.End();
}
}
3、WebService文件增加头属性
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
[SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)]
public class getData : System.Web.Services.WebService
{
#region 1、获取设备信息
[WebMethod]
public void GetAllDeviceData()
{
string sql = @"select devid,jfid,devname from JfDevice";
DataTable dtTable = AosySql.ExecuteforDataSet(sql).Tables[0]; //获取数据库数据的方法,使用的数据库访问类,根据自身情况调整
StringBuilder sb = new StringBuilder();
if (dtTable.Rows.Count > 0)
{
foreach (DataRowView drv in dtTable.DefaultView)
{
sb.Append("{\"DevId\":\"" + drv["devid"].ToString() + "\",");
sb.Append("\"DevName\":\"" + drv["devname"].ToString() + "\",");
sb.Append("\"JfId\":\"" + drv["jfid"].ToString() + "\"},");
}
}
string result = "[" + sb.ToString().TrimEnd(',') + "]";
Tools.WriteResult(HttpContext.Current.Request["jsoncallback"], result);
}
}
4、将WebService发布到IIS后,在其他系统中的html页面中调用,如下代码所示:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function () {
getValueFromWebService();
});
//查询webservice
function webservice(url, callback) {
$.ajax({
type: 'get',
url: url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
success: function (result) {
callback(result);
}
});
};
function getValueFromWebService() {
webservice('http://192.168.33.158/XXXX/WebService/getData.asmx/GetAllDeviceData',
function (obj) {
var data = obj;
//成功
$.each(data, function (key, item) {
// 添加项目内容到ul列表中
$('<li>', { text: formatItem(item) }).appendTo($('#room'));
});
});
}
function formatItem(item) {
return item.DevId + ' / ' + item.DevName + ' / ' + item.JfId;
}
</script>
</head>
<body>
<ul id="room">
</ul>
</body>
</html>