webservice 代碼
1 /// <summary> 2 /// MESService 的摘要說明 3 /// </summary> 4 [WebService(Namespace = "http://tempuri.org/")] 5 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 6 //[System.ComponentModel.ToolboxItem(false)] 7 // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 8 [System.Web.Script.Services.ScriptService] 9 public class MESService : System.Web.Services.WebService 10 { 11 12 [WebMethod(Description = "")] 13 public string GetDataReturnStr(string strXML) 14 { 15 //你的結果處理 16 #region 處理數據 17 18 #endregion 19 return Common.JsonHelper.SerializeToJson(new Student() { id = "1", name = "測試" }); 20 } 21 22 23 } 24 [Serializable] 25 public class Student 26 { 27 public string id { get; set; } 28 public string name { get; set; } 29 }
webservice 文件中需要添加的信息
// 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。
[System.Web.Script.Services.ScriptService]
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 代碼
1 $.ajax({ 2 async: true, 3 type: "post", 4 url: "http://localhost:41453/IDataServer/MESService.asmx/GetDataReturnStr", 5 data: "{strXML:'123123123'}", 6 dataType: "json", 7 contentType: "application/json; charset=utf-8", 8 success: function (json) { 9 var dataObj = eval("(" + json.d + ")"); 10 alert(dataObj.id + '\r\n' + dataObj.name); 11 }, 12 error: function () { 13 14 }, 15 complete: function () { 16 } 17 });
這樣就可以實現 ajax 訪問webservice接口了