Web Service 端,建立一个 Service1.asmx 页面:
Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel Imports System.Web.Script.Services
' 若要允许使用 ASP.NET AJAX 从指令码呼叫此 Web 服务,请取消批注下一行。
呼叫端(客户端),建立 GetAjaxData.htm 的静态页面,透过 jQuery ajax 取数据:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" > <head> <title>jQuery ajax + Asp.net asmx (web service)</title> <script type="text/javascript" src=""></script> </head> <script type="text/javascript"> function validate() { var ret = ""; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Service1.asmx/HelloWorld", dataType: "json", data: "{'m':'YYY', 't': 'XXX'}", success: function(data) { $.each(data.d, function(index, element) { ret += index + " - " + element + "\n"; }); alert(ret); $("#show").html(ret.replace(/\n/g, "<br />")); } }); } function validateXML() { var ret = ""; $.ajax({ type: "POST", url: "Service1.asmx/HelloXML", contentType: "application/json; charset=utf-8", data: "{'m':'YYY', 't': 'XXX'}", dataType: "xml", success: function(data) { $(data).find("string").each(function(index) { ret += index + " - " + $(this).text() + "\n"; }); alert(ret); $("#show").html(ret.replace(/\n/g, "<br />")); } }); } </script> <body> <div> <input type="button" id="btnJson" name="btnJson" value="Ajax Json" onclick="validate();" /> <input type="button" id="btnXml" name="btnXml" value="Ajax XML" onclick="validateXML();" /> <div id="show"> </div> </div> </body> </html>
为了确定回传的格式,透过 IE9 的开发人员工具把出 Response 的内容做验证。
按【Ajax Json】钮的执行结果:
按【Ajax XML】钮的执行结果: