ajax跨域调用webservice方法实例
发布时间:2020-12-16 00:45:46 所属栏目:百科 来源:网络整理
导读:webservice代码部分: [WebMethod(Description = "这是一个描述")] public void GetTIM() { try { SqlDataAdapter da = new SqlDataAdapter("select * from Status",Con); DataSet ds = new DataSet(); da.Fill(ds); ListThingNetwork Stulis = new ListThin
webservice代码部分: [WebMethod(Description = "这是一个描述")] public void GetTIM() { try { SqlDataAdapter da = new SqlDataAdapter("select * from Status",Con); DataSet ds = new DataSet(); da.Fill(ds); List<ThingNetwork> Stulis = new List<ThingNetwork>(); DataTable dt = ds.Tables[0]; foreach (DataRow row in dt.Rows) { ThingNetwork st = new ThingNetwork(); st.Ieee = row["Ieee"].ToString(); st.CO2 = row["CO2"].ToString(); Stulis.Add(st); } string result = JsonConvert.SerializeObject(Stulis); if (!string.IsNullOrEmpty(Context.Request["callback"])) { result = Context.Request["callback"] + "(" + result + ")"; } Context.Response.Clear(); Context.Response.Charset = "UTF-8"; Context.Response.ContentType = "text/plain"; Context.Response.Write(result); //这里是json个文本 Context.Response.End(); } catch (Exception ms) { System.Web.UI.Page tt = new System.Web.UI.Page(); tt.Response.Write(ms.Message); } finally { Con.Close(); } }config配置代码: <system.web>
<compilation debug="true" >
</compilation>
<!--
通过 <authentication> 节,可配置
ASP.NET 用于识别进入用户的
安全身份验证模式。
-->
<authentication mode="Windows" />
<!--
通过 <customErrors> 节,可以配置
在执行请求的过程中出现未处理的错误时要执行
的操作。具体而言,
开发人员通过该节可配置要显示的 html 错误页,
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<webServices>
<protocols>
<add name="HttpGet" /> ------这里一定要配置
<add name="HttpPost" />
<add name="HttpSoap" />
</protocols>
</webServices>
</system.web>
前端代码部分: $.ajax({ url: 'http://localhost:1756/WebService.asmx/GetTIM?callback=?',dataType: 'jsonp',data: {},jsonp: 'jsoncallback',contentType: 'application/json; charset=utf-8',success: function (data) { $.each(data,function (i,n) { alert(n.Ieee); }); },error: function () { alert('错误!'); } });这样就OK啦!!! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |