ajax跨域调用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();
- }
- }
- <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" /> ------<span style="color:#ff0000;">这里一定要配置</span>
- <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
转自:http://blog.csdn.net/meiminjun2012/article/details/17304651