webservice服务端代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace myWebService
{
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod(Description = "获取当前数据库下指定表结构信息")]
public void getDBTableInfos(string tableName)
{
HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
string jsonCallBackFunName = string.Empty;
jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
string jsonStr=string.Empty;
//此处省略生成jsonStr数据代码....
HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr)));
}
}
}
前台jsonp跨域调用webservice代码:
$.ajax({
type: "get",
url: "http://localhost:17006/WebService.asmx/getDBTableInfos?jsoncallback?", //所请求的webservice服务url地址
dataType: "jsonp",
//contentType: "application/json;charset=utf-8", //通过jsonp请求时,此处设置该属性值无效
jsonp: 'jsoncallback',
data: "tableName=XX_User",
success:function(result) { //返回json类型数据
alert(result);
}
});
注意事项:
1、检查当前请求项目web.config是否包含如下配置节,
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
2、检查webservice所在的服务应用程序的web.config是否包含一下配置节,
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
3、webservice服务端代码页面,必须设置http头部相应的content-Type(同时可以在webservice部署的网站或者虚拟目录属性下"http头"选项下新增自定义http头:Content-Type:application/json;charset=utf-8;),否则浏览器会以text/xml的类型显示,导致无法回调处理函数。