Ajax 调用webservice 解决跨域请求和发布到服务器后本地调用成功外网失败的问题
Ajax 调用webservice 解决跨域请求和发布到服务器后本地调用成功外网失败的问题
webservice 代码
webservice 文件中需要添加的信息
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
/// /// MESService 的摘要说明 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //[System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [System.Web.Script.Services.ScriptService] public class MESService : System.Web.Services.WebService { [WebMethod(Description = "")] public string GetDataReturnStr(string strXML) { //你的结果处理 #region 处理数据 #endregion return Common.JsonHelper.SerializeToJson(new Student() { id = "1", name = "测试" }); } } [Serializable] public class Student { public string id { get; set; } public string name { get; set; } }
WebConfig 文件中需要添加节点
1、解决跨域访问的问题
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" /> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type" /> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol></system.webServer>
2、解决本地调用成功,外网调用失败的问题
<system.web> <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="Documentation"/> </protocols> </webServices></system.web>
Ajax 调用
$.ajax({ async: true, type: "post", url: "http://localhost:41453/IDataServer/MESService.asmx/GetDataReturnStr", data: "{strXML:'123123123'}", dataType: "json", contentType: "application/json; charset=utf-8", success: function (json) { var dataObj = eval("(" + json.d + ")"); alert(dataObj.id + '\r\n' + dataObj.name); }, error: function () { }, complete: function () { } });