AJAX 异步调用WebService
页面中的脚本如下:
function btnInvoke_onclick(){ var theName = document.getElementById("tbName").value; SimpleWebService.SayHello(theName, onSayHelloSucceeded);//此处出错。}function onSayHelloSucceeded( result ){ document.getElementById("result").innerHtml = result;}
<from id="form1" runat="server"> <asp:ScriptManager ID="sm" EnablePateMethods="true" runat="server"> <Service> <asp:ServiceReference Path="Services/SimpleWebService.asmx" /> </Service> </asp:ScriptManager> <div> <input id="tbName" type="text" /> <input id="btnInvoke" type="button" value="Say Hello" onclick="return btnInvoke_onclick()" /> <div id="result" ></div> <div></from>
......using System.Web.Script.Service;......namespace WebApplication1{ .... .... [ScriptService] public class SimpleWebService : System.Web.Services.WebService { [WebMethod] public string SayHello( string name ) { return string.Format( "Hello {0}!", name ); } } }
WebApplication1.SimpleWebService.SayHello(theName, onSayHelloSucceeded);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>jQuery Ajax 调用 WebService 返回数据表(DataTable)的方法。</title> <script type="text/javascript" src="jquery-1.5.js"></script> <script type="text/javascript"> function ParseDate(jsonDate) { var date = new Date(parseInt(jsonDate.substr(6))); return date.toLocaleString(); } function GetData() { $.ajax({ type: "post", //注意这里是 post url: "WebService.asmx/GetDataTable", data: "{\"id\":\"8888\"}", contentType: "application/json;charset=utf-8", //提交数据的方法格式 dataType: "json", //返回数据的格式 success: function (result) { //你可以 alert(result.d)看数据返回的格式 data = jQuery.parseJSON(result.d); t = "<table border='1'>"; $.each(data, function (i, item) { t += "<tr>"; t += "<td>" + item.UserId + "</td>"; t += "<td>" + item.Name + "</td>"; t += "<td>" + item.Count + "</td>"; t += "<td>" + ParseDate(item.CreateDate)+ "</td>"; t += "</tr>"; }) t += "</table>"; $("#result").html(t); }, error: function (result) { alert(result.responseText); } }); } window.onload = GetData; </script></head><body> <div id="result"></div></body></html>
[解决办法]
在web service中写成这样试试[WebService(Namespace = "http://tempuri.org/")]
[System.Web.Script.Services.ScriptService]
public class SimpleWebService : System.Web.Services.WebService
然后再用你原来的方法试试,看会不会出错
[解决办法]
Services/SimpleWebService.asmx 这里为什么会有个目录Services呢?